<?php

namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\Models\User;
use PDF;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;


class AccountclosureController extends Controller
{
   

    public function form(Request $request)
    {     
        $key = $request['key'];

        $values1 = [
            'updated_at'=>NOW(),
        ];
DB::table('comm_unique_identifier')->where('unique_identifier_value',$key)->whereNull('updated_at')->update($values1);

    
       $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$key)->where('updated_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 15 MINUTE)'))->get();
          
          if(count($uniquevalue) == 0){
              return redirect('pageerror')->with('error', "This link has expired or already been used."); 
          }






        $datacheck = DB::table('comm_account_closure')->where('keys1',$key)->get();

        if(count($datacheck) >= 1){ 
            return redirect('pageerror')->with('error', "This link has expired or already been used.");
        }



        $fullUrl = $request->fullUrl();
        $parsedUrl = parse_url($fullUrl, PHP_URL_PATH);

        // Isolate the word before the '?'
        $path = strtok($parsedUrl, '?');

        // Extract the last part of the path
        $segments = explode('/', $path);
        $formname = end($segments);

        $key = $request['key'];
     




        $data = DB::table('comm_unique_identifier')->select('created_at','userid')->where('unique_identifier_value',$request['key'])->get();    
        $formattedDate = $data[0]->created_at;
 
        $uid = $data[0]->userid;

        $user_data = User::where('uid', $uid)->first();
       
               $param1 = $request['key'];
        
               if($param1 != '')
               {
                   $uniquevalue1 = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->get();
                   if(count($uniquevalue1) == 0){
                       return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match."); 
                   }
                 $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->where('created_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 1 DAY)'))->get();
                 //  $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->where('created_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 15 MINUTE)'))->get();
                   
                   if(count($uniquevalue) == 0){
                       return redirect('pageerror')->with('error', "VALID FOR 24 HOURS ONLY,The URL is expired."); 
                   }
       
               }else {
                   return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match.");
               }
           
       
               
               $user_email = User::where('mail', $user_data->mail)->first();
       
               if ($user_email) 
               {
                    $loginCustom = User::where('name', $user_data->name)
                   ->where('pass',$user_data->pass)
                   ->first();
                  
                   if($loginCustom == '') 
                   {
                     
                       return redirect('pageerror')->with('error', "There was a problem, please try again");
                       
                   }else 
                   {
                          
       
                       $users = User::where('name', $user_data->name)->first();
       
       
                          
                       if ($users) {
                           
                           Auth::login($users);
       
                       
                        
                                    $user = Auth::user();
                         
       
                                    $ip = $request->get('client_ip');
                                    
                                    $fullUrl = $request->fullUrl();
                                   $result = file_get_contents("http://ip-api.com/php/{$ip}");
                                   $details = unserialize($result);
                                   $country = $details['country'];
                           
                            
                                    $logData = [
                                        'date_time' => now()->format('Y-m-d H:i:s'), 
                                        'uid' => $user->uid,
                                        'country' => $country,
                                        'ip_details' => $details,
                                        'fullUrl'=> $fullUrl,
                                        
                                    ];
                                
                                    $logFile = 'userlogs/userlog.txt';
                                    $backupSizeLimit = 500 * 1024 * 1024; // 500MB
                                    
                                    // Ensure the logs directory exists
                                    if (!Storage::exists('userlogs')) {
                                        Storage::makeDirectory('userlogs');
                                    }
                            
                            
                                    // Check file size and backup if needed
                                    if (Storage::exists($logFile) && Storage::size($logFile) >= $backupSizeLimit) {
                                        $backupName = 'userlogs/userlog_backup_' . now()->format('Y-m-d_H-i-s') . '.txt';
                                        Storage::move($logFile, $backupName);
                                        Storage::put($logFile, ""); // Create new empty file
                                    }
                                
                                    // Append log data
                                    Storage::append($logFile, json_encode($logData, JSON_PRETTY_PRINT));
                            
                               
                                  
       
                                    if ($user && $user->b2b_uid) {
       
                                       if ((in_array('4', explode(',', $user->b2b_perm)))) {
                                           
                                       
                                       } else {
                                      
                                          return redirect('pageerror')->with('error', "User has no permission to access the form.");
                                      
                                       
                                       }
                                       
                                       $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->update([
                                           "submitted_by" => $user->uid,
                                           "user_type" => 'secondary',
                                       ]);
       
       
                                        $user = DB::table('users')->where('uid', $user->b2b_uid)->first();
                                    }
       
       
       
       $path = request()->path(); 
                                   // 	if ($user) 
                                   // 	{
                                       //Auth::login($user);
                               // dd($request['formname']);
                           if($path == 'revenueshareforms')
                           {
                             
                                return redirect()->route('revenueform', ['key' => $request['key'], 'username' => $user->name]);
       
                           }
                           if($path == 'Contentmappingform')
                           {
                              
                                return redirect()->route('content_forms', ['key' => $request['key'], 'username' =>  $user->name]);
       
                           }
                           
                           if($path == 'accountclosureform')
                           {
                                
                                return redirect()->route('account_form', ['key' => $request['key'], 'username' =>  $user->name]);
       
                           }
                           if($path == 'youtubeoac')
                           {
                               
                                return redirect()->route('youtube_oacs', ['key' => $request['key'], 'username' =>$user->name]);
       
                           }
       
       
                                       
                                       
                       }
                       else{
                           return redirect('pageerror')->with('error', "There was a problem, please try again");
                               }
                   
                   
                       }          
                   }else{
                       return redirect('pageerror')->with('error', "There was a problem, please try again");
                }
       
    }
    public function forms(Request $request,$key,$username)
    {     




        $param1 = $key;
        $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$key)->where('updated_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 15 MINUTE)'))->get();
           
        if(count($uniquevalue) == 0){
            return redirect('pageerror')->with('error', "This link has expired or already been used."); 
        }

        if($param1 != '')
        {
            $uniquevalue1 = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->get();
            if(count($uniquevalue1) == 0){
                return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match."); 
            }
            $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->where('created_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 1 DAY)'))->get();

            if(count($uniquevalue) == 0){
                return redirect('pageerror')->with('error', "VALID FOR 24 HOURS ONLY,The URL is expired."); 
            }

        }else {
            return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match.");
        }
    


        

        $data = DB::table('comm_account_closure')->where('keys1',$key)->get();
      

       $users = DB::table('users')->where('name',$username)->first();

       $like_to_wait_value = DB::table('comm_like_to_wait')
       ->where('like_to_wait_id', '1')
       ->value('like_to_wait_value');
    
    //    if(count($data) >= 1){
    //     return redirect('pageerror')->with('error', "This link has expired or already been used."); 
    //     }


        if(count($data) >= 1){
            $data = 0;
            return view('accountclosureform',compact('data','key','users','like_to_wait_value'));
        }
        $data=1;
        return view('accountclosureform',compact('data','key','users','like_to_wait_value'));

    }
    public function formsubmit(Request $request)
    {    

        $elaborate_reason = '';
      
        $email = $request->input('email1');
        $name = $request->input('username1');
        $userid = $request->input('user_id1');
        $closureOption = $request->input('close');
        $rating = $request->input('satisfied');
        $reasonaccount = $request->input('account');
        $distributor = $request->input('options');
    
        $service = $request->input('service');
        $product = $request->input('product');

        if($service != ''){
           $elaborate_reason = $service;
        }else{
           $elaborate_reason = $product;
        }
        $comment = $request->input('comments') ?? $request->input('commentss');



       
            $param1 = $request->input('key');

            $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->where('updated_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 15 MINUTE)'))->get();
          
        if(count($uniquevalue) == 0){
            return redirect('pageerror')->with('error', "This link has expired or already been used."); 
        }
        
            if($param1 != '')
            {
                $uniquevalue1 = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->get();
                if(count($uniquevalue1) == 0){
                    return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match."); 
                }
                $uniquevalue = DB::table('comm_unique_identifier')->where('unique_identifier_value',$param1)->where('created_at', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 1 DAY)'))->get();

                if(count($uniquevalue) == 0){
                    return redirect('pageerror')->with('error', "VALID FOR 24 HOURS ONLY,The URL is expired."); 
                }

            }else {
                return redirect('pageerror')->with('error', "Your UNIQUEKEY doesn't match.");
            }
        


       
       $counts = DB::table('comm_unique_identifier')->where('unique_identifier_value', $request->input('key'))->where('type','luna')->count();



       $today = date('ymd'); // 250515 (for May 15, 2025)
       $lastFormId = DB::table('comm_account_closure')
           ->where('form_id', 'like', $today . '%')
           ->orderBy('form_id', 'desc')
           ->value('form_id');
       
       $lastSequence = $lastFormId ? intval(substr($lastFormId, -3)) : 0;
       $newSequence = str_pad($lastSequence + 1, 3, '0', STR_PAD_LEFT);
       
       $formId = (int)($today . $newSequence);

       
      

if($counts > 0){


    $values = [
        'type'=>'1',
        'form_id' => $formId,
        'email' => $email,
        'username' => $name,
        'userID' => $userid,
        'would_you_like_to_wait' => $closureOption,
        'rating' => $rating,
        'reason' => $reasonaccount,
        'elaborate_reason' => $elaborate_reason,
        'other_distrubutor' => $distributor,
        'comments' => $comment,
        'keys1' => $request->input('key')
    ];

    DB::table('comm_account_closure')->insert($values);

}else{


        $data = DB::table('comm_tbl_smthub_ticket')->where('keys1', $request->input('key'))->get();

        $values = [
            'form_id' => $data[0]->id,
            'email' => $email,
            'username' => $name,
            'userID' => $userid,
            'would_you_like_to_wait' => $closureOption,
            'rating' => $rating,
            'reason' => $reasonaccount,
            'elaborate_reason' => $elaborate_reason,
            'other_distrubutor' => $distributor,
            'comments' => $comment,
            'keys1' => $request->input('key')
        ];
    
        DB::table('comm_tbl_smthub_ticket')->where('keys1', $request->input('key'))->update(['status' => "Admin Action Needed"]);
        DB::table('comm_account_closure')->insert($values);
    }
        return redirect()->back()->with('success', 'Account Closure Form Submitted Successfully.');

    }

   
    

   
}



