<?php

namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use DB;
use 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 Mail;
use Illuminate\Support\Facades\Storage;

class ContentmappingController extends Controller
{
    

    public function getcorresvalues(Request $request)
    {
        $uid = $request->input('uid');
        $upcs = $request->input('upc');
    
        $parts = explode(' - ', $upcs);

// Take the first part (UPC number)
$upc = trim($parts[0]);

        $Country = DB::select("SELECT value FROM profile_values WHERE fid = 9 AND uid = ?", [$uid]);
    
        $Website = DB::select("SELECT value FROM profile_values WHERE fid = 7 AND uid = ?", [$uid]);

        $city = DB::select("SELECT city,state FROM signup_temp WHERE uid = ?", [$uid]);

        $primary = DB::select("SELECT DISTINCT artist FROM release_table WHERE upc = ? AND uid = ? AND artist != ''", [$upc, $uid]);

        $secondary = DB::select("SELECT DISTINCT sec_art FROM release_table WHERE upc = ? AND uid = ? AND sec_art != ''", [$upc, $uid]);

                
       

        return response()->json([
            'country'   => $Country,
            'website'   => $Website,
            'city'      => $city,
            'primary'   => $primary,
            'secondary' => $secondary,
        ]);
        }

    public function usersearch(Request $request)
    {
        $query = $request->input('q');
    
        $users = DB::table('users')->where('name', 'like', '%' . $query . '%')
                      ->limit(10) // Limit to 10 results
                      ->get();
    
        return response()->json($users);
    }

    
    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_content_mapping')->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_content_mapping')->where('keys1',$key)->get();
        $users = DB::table('users')->where('name',$username)->first();
       // $upclist = DB::table('release_table')->where('uid',$users->uid)->get();
        $upcDetails = [];  // This will hold the final result with the concatenated string

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

    }
    public function getupcDetails2(Request $request)
    { 
    //     $upclist = DB::table('release_table')
    // ->where('upc', 'like', '%' . $request->input('query') . '%')
    // ->where('uid', $request->input('user_id'))->get();
   
    $upclist = DB::table('release_table')
    ->where('upc', 'like', '%' . $request->input('query') . '%')
    ->where('uid', $request->input('user_id'))
    ->limit(10)
    ->get();
    

//dd($upclist);    //
        $upcDetails = [];  // This will hold the final result with the concatenated string

        foreach ($upclist as $upc) {
            // Get album name
            $album = DB::table('album_metadata')
                        ->select('value')
                        ->where('upc_id', $upc->upc) // Use $upc->upc to access the UPC
                        ->where('tag', 'album')
                        ->first(); // Use first() instead of get()
        
            // Get album version
            $albumver = DB::table('album_metadata')
                          ->select('value')
                          ->where('upc_id', $upc->upc)
                          ->where('tag', 'albumversion')
                          ->first(); // Use first() instead of get()
        
            // Get artist title
            $artist = DB::table('album_metadata')
                        ->select('value')
                        ->where('upc_id', $upc->upc)
                        ->where('tag', 'artist')
                        ->first(); // Use first() instead of get()
     
            // Concatenate the values to form the desired string

            $albumName = $album ? $album->value : '';
$version = $albumver ? $albumver->value : '';
$artistName = $artist ? $artist->value : '';

$formattedString = $upc->upc . ' - ';

if ($albumName || $version) {
    $formattedString .= trim($albumName . ' + ' . $version, ' + ');
}

if ($artistName) {
    // Add comma if album/version part exists
    if ($albumName || $version) {
        $formattedString .= ' , ';
    }
    $formattedString .= $artistName;
}

$upcDetails[] = $formattedString;

            //  if ($album && $albumver && $artist) {
            //     // Form the desired format: "album + version, artist"
            //     $upcDetails[] = $upc->upc .' - '. $album->value . ' + ' . $albumver->value . ' , ' . $artist->value;
            //  }
         }

         return response()->json(['upcDetails' =>$upcDetails]);
    }

   
  
  
    public function contentformsubmit(Request $request)
    {    


  // dd($request->all());    


//$datas = json_decode($request->input('AllData'));

//  $encoded = $request->input('AllData');

//     $json = urldecode(base64_decode($encoded));
//     $datas = json_decode($json, true);

// $urls = [];

function generateRandomString($length = 16) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return substr(str_shuffle(str_repeat($characters, ceil($length / strlen($characters)))), 0, $length);
}

//    dd($datas);
$i = 0;
// Loop through the decoded array to get the URL fields

$datas = json_decode($request->input('AllData'));
foreach ($datas as $store) {
    foreach ($store->Choosedata as $key => $iem) {

        if (isset($iem->JioSaavn0)) {

            $base64String = $iem->JioSaavn0;
            if (preg_match('/^data:image\/(\w+);base64,/', $base64String, $type)) {
                // Remove the prefix
                $data = substr($base64String, strpos($base64String, ',') + 1);
                // Decode the base64 string
                $data = base64_decode($data);

                if ($data === false) {
                    echo "Base64 decode failed";
                }

                // Generate a unique filename
                $filename = '/uploadfiles/' . 'downloaded_image_' . generateRandomString(8) . '.jpg';

                // Save the image to the public path
                $path = public_path($filename);
                file_put_contents($path, $data);
                $iem->JioSaavn0 = $filename;
            }

        } else if (isset($iem->Zing0)) {
            $base64String = $iem->Zing0;
            if (preg_match('/^data:image\/(\w+);base64,/', $base64String, $type)) {
                // Remove the prefix
                $data = substr($base64String, strpos($base64String, ',') + 1);
                // Decode the base64 string
                $data = base64_decode($data);

                if ($data === false) {
                    echo "Base64 decode failed";
                }

                // Generate a unique filename
                $filename = '/uploadfiles/' . 'downloaded_image_' . generateRandomString(8) . '.jpg';

                // Save the image to the public path
                $path = public_path($filename);
                file_put_contents($path, $data);
                $iem->Zing0 = $filename;
            }
        }else if (isset($iem->Boomplay3)) {
            $base64String = $iem->Boomplay3;
            if (preg_match('/^data:image\/(\w+);base64,/', $base64String, $type)) {
                // Remove the prefix
                $data = substr($base64String, strpos($base64String, ',') + 1);
                // Decode the base64 string
                $data = base64_decode($data);

                if ($data === false) {
                    echo "Base64 decode failed";
                }

                // Generate a unique filename
                $filename = '/uploadfiles/' . 'downloaded_image_' . generateRandomString(8) . '.jpg';

                // Save the image to the public path
                $path = public_path($filename);
                file_put_contents($path, $data);
                $iem->Boomplay3 = $filename;
            }
        }
    }
    $i++;
}

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




$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.");
}





// dd($request->input('key'));

$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_content_mapping')
    ->where('id', 'like', $today . '%')
    ->orderBy('id', 'desc')
    ->value('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){
    $sid = DB::table('comm_content_mapping')->insertGetId([
        'id' => $formId,
        'userid' => $request->input('Uid'),
        'username' => $request->input('Usernameid'),
        'email' => $request->input('Emailid'),
        'keys1' => $request->input('key'),
        'action_needed' => $request->input('Action_need'),
        'type'=>'1',
    ]);
    
 
}else{

    $sid = DB::table('comm_content_mapping')->insertGetId([
        'id' => $data[0]->id,
        'userid' => $request->input('Uid'),
        'username' => $request->input('Usernameid'),
        'email' => $request->input('Emailid'),
        'keys1' => $request->input('key'),
        'action_needed' => $request->input('Action_need'),
    ]);
  
}  

$insertedRow = DB::table('comm_content_mapping')->where('ids', $sid)->first();

$sid = $insertedRow->id;


DB::table('comm_tbl_smthub_ticket')->where('keys1', $request->input('key'))->update(['status' => "Admin Action Needed"]);
foreach($datas as $items) {
    $upc = $items->upc;
    $artistname = $items->artistname;
    $Choosedata = json_encode($items->Choosedata);

    $values = [
        'tbl_content_mapping_id' => $sid,
        'upc' => $upc,
        'artist_name' => $artistname,
        'choose_store' => $Choosedata,
    ];


    $id = DB::table('comm_store_details')->insert($values);
}


return response()->json(['message' => 'Completed..'], 200);


     
        return redirect()->back()->with('success', 'Content Mapping Request Form Submitted Successfully.');

    }



   
  
}



