<?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 Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;


class YoutubeController extends Controller
{
   
    public function getartistnames(Request $request)
    { 

        $results = DB::select("
    SELECT
        MAX(CASE WHEN am.tag = 'artist' THEN am.value END) AS artist,
        MAX(CASE WHEN am.tag = 'artistrole' THEN am.value END) AS artistrole,
        MAX(CASE WHEN am.tag = 'sec_artist' THEN am.value END) AS sec_artist,
        MAX(CASE WHEN am.tag = 'secartist_role' THEN am.value END) AS secartist_role
    FROM
        audio a
    JOIN
        audio_metadata am ON am.vid = a.vid
    WHERE
        a.isrc = ?
        AND am.tag IN ('artist', 'artistrole', 'sec_artist', 'secartist_role')
    GROUP BY
        a.isrc
", [$request['isrc']]);

if (!empty($results)) {
    $row = (array) $results[0]; 

    $output = [];

    if (!empty($row['artist']) && !empty($row['artistrole'])) {
        $output[] = "{$row['artist']} - {$row['artistrole']}";
    }

    if (!empty($row['sec_artist']) && !empty($row['secartist_role'])) {
        $secArtists = explode(',', $row['sec_artist']);
        $secRoles = explode(',', $row['secartist_role']);

        foreach ($secArtists as $index => $artist) {
            $role = $secRoles[$index] ?? '';
            $output[] = trim($artist) . ' - ' . trim($role);
        }
    }

    return response()->json(['artists' => $output]);  // Always return valid JSON

   // return response()->json($output);

}
    }

    public function checkbadflags(Request $request)
    {
       
        $uid = $request->input('uid');

        $sel_fra_count = DB::table('flag_comment')
        ->where('uid', $request['uid'])
        ->whereIn('flagtype', ['FraudStrike', 'fraud_streaming'])
        ->count();

        $response = 'No';
    
    if ($sel_fra_count != 0) {
      
     
//Fraud payment list
$sel_fra_sdt_count1 = DB::table('users')
->where('possible_fraud', 1)
->where('under_investigation', 0)
->where('paypal_issue', 0)
->where('indianpaypal', 0)
->where('fraud_streaming', 0)
->where(function ($query) {
    $query->whereNull('bank_transfer')
          ->orWhere('bank_transfer', 0);
})
->where('uk_vat_flag', 0)
->where('paidtorn', 0)
->where('uk_vat_highlights', 0)
->where('uid',$uid)
->count();

if ($sel_fra_sdt_count1 != 0) {
    $response = 'Yes';
} else {
    $response = 'No';
}

        }
     else {
        $response = 'No';
    }

    

  

    $cidred = DB::select("SELECT COUNT(*) AS cnt FROM flag_comment WHERE INSTR(comment, 'CID red') > 0 AND uid = ?", [$uid]);

    $cidamber = DB::select("SELECT COUNT(*) AS cnt FROM flag_comment WHERE INSTR(comment, 'CID amber') > 0 AND uid = ?", [$uid]);

    $cidredflag = DB::select("SELECT COUNT(*) AS cnt FROM flag_comment  where uid='yt_network_abuse' AND uid = ?", [$uid]);


    if (!empty($cidred) && $cidred[0]->cnt > 0) {
        $response = 'Yes';
    }

    if (!empty($cidamber) && $cidamber[0]->cnt > 0) {
        $response = 'Yes';
    }
    if (!empty($cidredflag) && $cidredflag[0]->cnt > 0) {
        $response = 'Yes';
    }



$flagcolors = DB::table('flag_comment')
->where('flagtype' , 'Copyright infringeme')
    ->where('uid', $uid)  
->count(); 

if($flagcolors > 0){
    $response = 'Yes';
}


  return response()->json(['badflag'=>$response]);
    }
    public function checkDuplicates(Request $request)
    {
        $artistURL = $request->input('artist');
        $topicURL = $request->input('topic');
        $upc = $request->input('upc');

        $firstPart = explode(' - ', $upc)[0];

   
        $result = DB::select(
            "SELECT COUNT(a.isrc) AS cnt
             FROM audio a
             JOIN album_distribution ad ON ad.upc = a.upc
             WHERE ad.distributors LIKE ?
               AND ad.blocked_stores NOT LIKE ?
               AND a.isrc = ?",
            ['%21%', '%21%', $firstPart]
        );


 $datasss = DB::table('comm_oac_form')->where('artist_channel_url', $artistURL)->get();

 if(count($datasss) > 0){
    
    $datasss1 = DB::table('comm_form_status')
    ->where('form_id', $datasss[0]->id)
    ->orderBy('id', 'desc')
    ->get();

    if(count($datasss1) > 0){
        $done = '1';
        
    }else{
        $done = '0';
    }


 }else{
    $done = '0';
 }
        $response = [
            'artist_channel_url' => DB::table('comm_oac_form')->where('artist_channel_url', $artistURL)->exists(),
            'artist_channel_urldone' => $done ,
            'topic_channel_url' => DB::table('comm_oac_form')->where('topic_channel_url', $topicURL)->exists(),
            'upc' => DB::table('comm_oac_form')->where('upc', $upc)->exists(),
            'youtubeisrc' => $result
        ];

        return response()->json($response);
    }

    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_oac_form')->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_oac_form')->where('keys1',$key)->get();
        $users = DB::table('users')->where('name',$username)->first();
       
   
        if(count($data) >= 1){
            $data = 0;
          
        
            return view('oacform',compact('data','key','users'));
        }
        $data=1;
        return view('oacform',compact('data','key','users'));

    }
    public function getupcDetails(Request $request)
    {     


        $query = $request->input('query');
    $userId = $request->input('user_id');

    $results = DB::table('release_table as rt')
        ->join('audio as a', 'a.upc', '=', 'rt.upc')
        ->where('rt.uid', $userId)
        ->where('a.isrc', '!=', 'DELETED')
        ->where(function($q) use ($query) {
            $q->where('a.isrc', 'like', "%$query%")
              ->orWhere('a.title_format', 'like', "%$query%")
              ->orWhere('rt.upc', 'like', "%$query%")
              ->orWhere('rt.releasetitle', 'like', "%$query%");
        })
        ->select('a.isrc', 'a.title_format', 'rt.upc', 'rt.releasetitle')
        ->limit(30)
        ->get();

    $upcDetails = [];

    foreach ($results as $res) {
        $approved = DB::select("
        SELECT a.isrc, dr.upc, dr.release_status 
        FROM audio a 
        JOIN discography_api_report dr ON dr.upc = a.upc 
        WHERE a.isrc = ? AND dr.release_status = 'Approved'
    ", [$res->isrc]);

    $inReview = DB::select("
    SELECT a.isrc, dr.upc, dr.release_status 
    FROM audio a 
    JOIN discography_api_report dr ON dr.upc = a.upc 
    WHERE a.isrc = ? AND dr.release_status = 'In Review'
", [$res->isrc]);

$denied = DB::select("
    SELECT arl.upc 
    FROM approved_releases_logs arl 
    LEFT JOIN audio a ON a.upc = arl.upc 
    WHERE a.isrc = ? AND arl.disapp_highlight = 1
", [$res->isrc]);


if (!empty($approved) || !empty($inReview) || !empty($denied)) {



        $upcDetails[] = "{$res->isrc} - {$res->title_format} - {$res->upc} - {$res->releasetitle}";

}
    }

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

    //     $upcDetails =[];
    //     $upclist = DB::table('release_table')->where('uid',$request['user_id'])->get();
    // foreach ($upclist as $upc) {
        
    //     // Get all non-deleted ISRCs for this UPC
    //     $isrcList = DB::table('audio')
    //         ->select('isrc')
    //         ->where('upc', $upc->upc)
    //         ->where('isrc', '!=', 'DELETED')
    //         ->get();
    
    //     // Get UPC-level title
    //     $upctitle = DB::table('release_table')
    //         ->select('releasetitle')
    //         ->where('upc', $upc->upc)
    //         ->first();
    
    //     foreach ($isrcList as $isrc) {
    
    //         $approved = DB::select("
    //         SELECT a.isrc, dr.upc, dr.release_status 
    //         FROM audio a 
    //         JOIN discography_api_report dr ON dr.upc = a.upc 
    //         WHERE a.isrc = ? AND dr.release_status = 'Approved'
    //     ", [$isrc->isrc]);
    
    //     $inReview = DB::select("
    //     SELECT a.isrc, dr.upc, dr.release_status 
    //     FROM audio a 
    //     JOIN discography_api_report dr ON dr.upc = a.upc 
    //     WHERE a.isrc = ? AND dr.release_status = 'In Review'
    // ", [$isrc->isrc]);
    
    // $denied = DB::select("
    //     SELECT arl.upc 
    //     FROM approved_releases_logs arl 
    //     LEFT JOIN audio a ON a.upc = arl.upc 
    //     WHERE a.isrc = ? AND arl.disapp_highlight = 1
    // ", [$isrc->isrc]);
    

    // if (!empty($approved) || !empty($inReview) || !empty($denied)) {

    
    //         // Get title format for each ISRC
    //         $isrctitle = DB::table('audio')
    //             ->select('title_format')
    //             ->where('isrc', $isrc->isrc)
    //             ->where('isrc', '!=', 'DELETED')
    //             ->first();
    
    //         if ($isrctitle && $upctitle) {
    //             $upcDetails[] = $isrc->isrc . ' - ' . $isrctitle->title_format . ' - ' . $upc->upc . ' - ' . $upctitle->releasetitle;
    //         }
    //    }
    // }
    // }

   

}


  

    public function fsacheck(Request $request)
{


    $uid =$request['uid'];

    $sel_fra_count = DB::table('flag_comment')
    ->where('uid', $request['uid'])
    ->whereIn('flagtype', ['FraudStrike', 'fraud_streaming'])
    ->count();

    $sel_fra_count = DB::table('flag_comment')
    ->where('uid', $uid)
    ->whereIn('flagtype', ['FraudStrike', 'fraud_streaming'])
    ->count();

if ($sel_fra_count != 0) {
    // Check the count of users records
    $sel_fra_sdt_count = DB::table('users')
        ->where('possible_fraud', 0)
        ->where('under_investigation', 0)
        ->where('paypal_issue', 0)
        ->where('indianpaypal', 0)
        ->where('fraud_streaming', 0)
        ->where(function ($query) {
            $query->whereNull('bank_transfer')
                  ->orWhere('bank_transfer', 0);
        })
        ->where('uk_vat_flag', 0)
        ->where('uid',$uid)
        ->count();

    if ($sel_fra_sdt_count != 0) {
        $fsacheck = '0';
    } else {
        $fsacheck = '1';
    }
} else {
    $fsacheck = '0';
}

if ($sel_fra_count != 0) {
    // Check the count of users records
    $sel_fra_sdt_count = DB::table('users')
        ->where('possible_fraud', 0)
        ->where('under_investigation', 0)
        ->where('paypal_issue', 0)
        ->where('indianpaypal', 0)
        ->where('fraud_streaming', 0)
        ->where(function ($query) {
            $query->whereNull('bank_transfer')
                  ->orWhere('bank_transfer', 0);
        })
        ->where('uk_vat_flag', 0)
        ->where('uid',$uid)
        ->count();

    if ($sel_fra_sdt_count != 0) {
        $fsacheck = 'No';
    } else {
        $fsacheck = 'Yes';
    }
} else {
    $fsacheck = 'No';
}


$upc = $request['upc'];

$sql1 = DB::table('moderation_hub_log')
    ->where('upc', $upc)
    ->orderBy('id', 'desc')
    ->first();

if ($sql1) {
    $upc1 = $sql1->upc;
    $admin_name = $sql1->admin_name;
    $admin_uid = $sql1->admin_uid;
    $action = $sql1->action;

    if ($admin_uid == '1201527' && $action == 'Assigned by') {
        echo "This $upc1 has a peterRN hub page.";
    } else {
        // Fetch from moderation_log if the first condition is not met
        $sql2 = DB::table('moderation_log')
            ->where('upc', $upc)
            ->orderBy('id', 'desc')
            ->first();

        if ($sql2) {
            $upc2 = $sql2->upc;
            $admin_uid2 = $sql2->admin_uid;
            $action2 = $sql2->action;

            if ($admin_uid2 == '1201527' && $action2 == 'Assigned by (Moderate)') {
                $petermod = '1';
            } else {
                $petermod = '0';
            }
        } else {
            $petermod = '0';
        }
    }
} else {
    $petermod = '0';
}


 
    $flagcolors = DB::table('flag_comment as fc')
    ->join('users as u', 'u.uid', '=', 'fc.uid')
    ->select(
        'fc.comment',
        DB::raw('CASE 
            WHEN fc.flagtype = "Approved" THEN "Approved"
            WHEN fc.flagtype = "Warning" THEN "Warning"
            WHEN fc.flagtype = "Suspicious" THEN "Suspicious"
            WHEN fc.flagtype = "Priority" THEN "Priority"
            WHEN fc.flagtype = "support_note" THEN "support_note"
            WHEN fc.flagtype = "Blacklisted" THEN "Blacklisted"
            WHEN fc.flagtype = "Blocklisted" THEN "Blocklisted"
            WHEN fc.flagtype = "Blocklisted" THEN "Blocklisted"
            WHEN fc.flagtype = "Copyright infringeme" THEN "Copyright infringeme"
            WHEN fc.flagtype = "FraudStrike" THEN "FraudStrike"
            WHEN fc.flagtype = "fraud_streaming" THEN "fraud_streaming" 
            WHEN fc.flagtype = "yt_network_abuse" THEN "yt_network_abuse"
            WHEN fc.flagtype = "Whitelisting YouTube channels" THEN "N/A"
            WHEN fc.flagtype = "Bulk actions" THEN "N/A"
            WHEN fc.flagtype = "Payments" THEN "payment"
            WHEN fc.flagtype = "payment" THEN "payment"   
            WHEN fc.flagtype = "Xpress" THEN "xpress"
            WHEN fc.flagtype = "Publishing Information" THEN "N/A"
            WHEN fc.flagtype = "publishing" THEN "publishing"
            WHEN fc.flagtype = "korean_account" THEN "korean_account"
            WHEN fc.flagtype = "star_artist" THEN "star_artist"
            ELSE "Unknown" 
        END as flag_color')
    )
    ->where('fc.uid', $uid)  
//->distinct() 
->get(); 
    $premium = DB::table('release_table as r')
    ->join('upc_distribution as ud', 'ud.upcid', '=', 'r.upc')
    ->where('ud.main_dis_option', 'premium')
    ->where('r.uid', $uid)
    ->distinct()
    ->count('r.upc');

    $stdcount = DB::table('users')
        ->where('uid', $uid)
        ->where(function ($query) {
         $query->whereNull('bank_transfer')
            ->orWhere('bank_transfer', 0);
         })
        ->where('paypal_issue', '0')
        ->where('indianpaypal', '0')
        ->where('paidtorn', '0')
        ->where('under_investigation', '0')
        ->where('possible_fraud', '0')
        ->where('fraud_streaming', '0')
        ->where('uk_vat_flag', '0')
        ->where('uk_vat_highlights', '0')
        ->count();

    if ($stdcount != 0) {
        $stdpayment = 'Yes';
    } else {
        $stdpayment = 'No';
    } 

    $status='Not Completed'; 
    $status2='Not Completed'; 
   // $ASANA_ACCESS_TOKEN = "2/1209617803499072/1209617783029095:791487594dcee0d44a07e014f56aff62";

   //$ASANA_ACCESS_TOKEN = "2/1208713570171412/1208713794959396:67d24263201288d58d4ce079e1e589fd";

  // $ASANA_ACCESS_TOKEN = "2/1210140826920800/1210140879288874:b607b892a611ba5064d411130cd71e21";
   $ASANA_ACCESS_TOKEN =  "2/1211168310822112/1211168315649523:58440002fc8d1d69f00221a33993ab1b";
    $guzzleClient = new GuzzleClient(['base_uri' => 'https://app.asana.com/api/1.0/']);
    $headers = ['Authorization' => 'Bearer ' . $ASANA_ACCESS_TOKEN, 'Content-Type' => 'application/json',];

    if ($ASANA_ACCESS_TOKEN === false) {
        echo "Please set the ASANA_ACCESS_TOKEN environment variable.\n";
        exit;
    }
    $subtaskId = $request['gid'];
    $subtaskId2 = $request['gid4'];
    // dd($subtaskId2);
    $ytasanaLink = '';
    $asanaLink = '';
    $slackLink = '';
    if($subtaskId){
        $response = $guzzleClient->request('GET', "tasks/$subtaskId", [
            'headers' => [
                'Authorization' => 'Bearer ' . $ASANA_ACCESS_TOKEN,
                'Content-Type' => 'application/json',
            ]
        ]);

        $task = json_decode($response->getBody(), true);
        
        $ytasanaLink = $task['data']['permalink_url'];

    $isCompleted = $task['data']['completed'];
    if ($isCompleted) {
        $status = 'Completed';
    }
    }

    if($subtaskId2){
        $response = $guzzleClient->request('GET', "tasks/$subtaskId2", [
            'headers' => [
                'Authorization' => 'Bearer ' . $ASANA_ACCESS_TOKEN,
                'Content-Type' => 'application/json',
            ]
        ]);

        $task = json_decode($response->getBody(), true);
        
        $asanaLink = $task['data']['permalink_url'];

    $isCompleted = $task['data']['completed'];
    if ($isCompleted) {
        $status2 = 'Completed';
    }
    }


    
    $artistpercentage = DB::table('artist_percentage')->where('uid', $request['uid'])->get();
    $username = DB::table('users')->select('name')->where('uid', $request['uid'])->value('name');

return response()->json(['artistpercentage'=>$artistpercentage,'fsacheck'=>$fsacheck,'status'=>$status,'asanaLink'=>$asanaLink,'petermod'=>$petermod,'premium'=>$premium,'flagcolors'=>$flagcolors, 'stdpayment' => $stdpayment, 'username' => $username]);


//return response()->json(['fsacheck'=>$fsacheck,'petermod'=>$petermod]);

}
   

    public function oacformsubmit(Request $request)
    {    

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

$image = $request->file('file');
$directoryPath = 'uploadfiles/';
$image->move(public_path($directoryPath),$image->getClientOriginalName());
$filepath = url($directoryPath).'/'.$image->getClientOriginalName();

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




$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_oac_form')
           ->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){

    $values = [
        'type'=>'1',
        'id' => $formId,
        'email' => $request['email1'],
        'username' => $request['username1'],
        'userid' => $request['userid'],
        'artist_name' => $request['thrid_in'],
        'country' => $request['four_in'],
        'artist_channel_url' => $request['five_in'],
        'artist_channel_id' => $request['six_in'],
        'video_url' => $request['seven_in'],
        'topic_channel_url' => $request['eitie_in'],
        'topic_video_url' => $request['ninen_in'],
        'upc' => $request['ten_in'],
        'dashboard' => $filepath,
        'keys1' =>  $request['key']
        
    ];
   // DB::table('comm_oac_form')->insert($values);
    if($request['formid'] == 'Yes'){

        $values['value_update'] = '1';


$datasss = DB::table('comm_oac_form')->where('artist_channel_url', $request['five_in'])->get();
if(count($datasss) == '0'){
    $datasss1 = DB::table('comm_oac_form')->where('topic_channel_url', $request['eitie_in'])->get();
    if(count($datasss1) == '0'){
        $datasss2 = DB::table('comm_oac_form')->where('upc', $request['ten_in'])->get();
        if(count($datasss2) > '0'){
            $iddd = $datasss2[0]->id;
            $keys1 = $datasss2[0]->keys1;
        }
    }
    else{
        $keys1 = $datasss1[0]->keys1;
    }
}else{
    $keys1 = $datasss[0]->keys1;
}


$values['old_key'] = $keys1;

        DB::table('comm_oac_form')->where('id',$iddd)->update($values);
    }
    else{
        DB::table('comm_oac_form')->insert($values);
    }
   
}else{


$values = [
            'id' => $data[0]->id,
            'email' => $request['email1'],
            'username' => $request['username1'],
            'userid' => $request['userid'],
            'artist_name' => $request['thrid_in'],
            'country' => $request['four_in'],
            'artist_channel_url' => $request['five_in'],
            'artist_channel_id' => $request['six_in'],
            'video_url' => $request['seven_in'],
            'topic_channel_url' => $request['eitie_in'],
            'topic_video_url' => $request['ninen_in'],
            'upc' => $request['ten_in'],
            'dashboard' => $filepath,
            'keys1' =>  $request['key']
            
        ];
        DB::table('comm_tbl_smthub_ticket')->where('keys1', $request->input('key'))->update(['status' => "Admin Action Needed"]);
        // Insert the data into the database
        //DB::table('comm_oac_form')->insert($values);

        if($request['formid'] == 'Yes'){

            $values['value_update'] = '1';



    

            $datasss = DB::table('comm_oac_form')->where('artist_channel_url', $request['five_in'])->get();
            if(count($datasss) == '0'){
                $datasss1 = DB::table('comm_oac_form')->where('topic_channel_url', $request['eitie_in'])->get();
                if(count($datasss1) == '0'){
                    $datasss2 = DB::table('comm_oac_form')->where('upc', $request['ten_in'])->get();
                    if(count($datasss2) > '0'){
                        $iddd = $datasss2[0]->id;
                        $keys1 = $datasss2[0]->keys1;
                    }
                }
                else{
                    $keys1 = $datasss1[0]->keys1;
                }
            }else{
                $keys1 = $datasss[0]->keys1;
            }


            $values['old_key'] = $keys1;


            DB::table('comm_oac_form')->where('id',$iddd)->update($values);
        }
        else{
            DB::table('comm_oac_form')->insert($values);
        }


    }
        return redirect()->back()->with('success', 'YouTube Official Artist Channel Request Form Submitted Successfully.');


    }


  
}



