<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Visitor;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Log;
use App\Models\Product;
use Illuminate\Validation\Rules\Exists;

class VisitorTradIndiaScheduleCronController extends Controller
{
    public function __construct() {}
    public function getConfig()
    {
        $config = DB::table('configs')->where('indiamartkey', 'tradindiakey')->first();
        return $config;
    }
    public function visitortradindiaschedulecron()
    {
        try {
          
            $configdata = $this->getConfig();

            //dd($configdata);
            if (isset($configdata)) {
                $id = $configdata->id;
                $indiamartkey = $configdata->indiamartkey;
                                                       
                $currentDate = Carbon::now('Asia/Kolkata')->format('Y-m-d');
                    
                if ($configdata->date !== $currentDate) {                  
                    DB::table('configs')->where('indiamartkey', 'tradindiakey')->update(['date' => $currentDate, 'limit' => 0]);                    
                } 
                $dbLimit =   DB::table('configs')->where('indiamartkey', 'tradindiakey')->pluck('limit')->first();

                if($dbLimit == 0){
                    $page = 1;
                    $limit = 50;
                }else{
                    $page = 2;
                    $limit = $configdata->limit;                     
                }

                $tradindiakey_url = 'https://www.tradeindia.com/utils/my_inquiry.html?userid=' . $configdata->user_id . '&profile_id=' . $configdata->profile_id . '&key=' . $configdata->key . '&from_date='.$currentDate.'&to_date='.$currentDate.'&limit='.$limit.'&page_no='.$page;
             
                $tradindia_event_id = $configdata->indiamart_event_id;
                $tradindia_user_id = $configdata->indiamart_user_id;

                $url = $tradindiakey_url;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_URL, $url);
                $result  = curl_exec($ch);
                $outData = json_decode($result, true);
                $recordsCount = count($outData);
                $log_data  = ['tradindiakey_url'=>$tradindiakey_url,'data'=>$outData]; 
                Log::build([
                    'driver' => 'single',
                    'path' => storage_path('logs/tradindia.log'),
                ])->info(["India Mart Log " =>$log_data]);

               if(is_array($outData) && count($outData) > 0){
                foreach ($outData as $response) {

                    $combinedStr = $response['generated_date'] . ' ' . $response['generated_time'];
                    $date = Carbon::createFromFormat('d F Y H:i:s', $combinedStr);
                    $created_at = $date->format('Y-m-d H:i:s');
                   
                    $remarks = "";
                    if (!empty($response['subject'])) {
                        $remarks .= "\nSubject: " . $response['subject'] . ";"; 
                    }
                    
                    if (!empty($response['message'])) {
                        $remarks .= "\nMessage: " . $response['message'] . ";"; 
                    }

                    if (!empty($response['product_name'])) {
                        $remarks .= "\nProduct Name: " . $response['product_name'] . ";";
                    }
                
                    $county_code = null;
                    $is_international = "false";
                    
                    if (!empty($response['sender_country'])) {
                        $county_code  =  DB::table('countries')->where('name',$response['sender_country'])->pluck('iso_code')->first();
                        $is_international =  $response['sender_country'] != "India" ? "true" : "false";
                    }
                    
                    $visitorData = [
                        'indiamart_query_id' => $response['rfi_id'] ?? '',
                        'name' => $response['sender_name'] ?? '',
                        'event_id' => $tradindia_event_id ?? '',
                        'customer_id' => $tradindia_user_id ?? '',
                        'mobile_no' => $response['sender_mobile'] ?? '',
                        'mobile_no2' => $response['sender_other_mobiles'] ?? '',
                        'mobile_no3' => $response['landline_number'] ?? '',
                        'remarks' =>  $remarks,
                        'state' => $response['sender_state'] ?? '',
                        'city' => $response['sender_city'] ?? '',
                        'visited_date'=>$created_at,    
                        'created_at' =>Carbon::now('Asia/Kolkata'),                     
                        'updated_at' => Carbon::now('Asia/Kolkata'),
                        "company_name"=>$response['sender_co'] ?? '',
                        "email" =>$response['sender_email'] ?? '',  
                        "country_code" =>  $county_code,
                        "is_international"  =>$is_international                                       
                    ];

                    $exits =  Visitor::where('indiamart_query_id',$response['rfi_id'])->exists();

                    if(!$exits){
                        $result = Visitor::create($visitorData);                      
                    }
                }
                
                // insert date                                   
                 DB::table('configs')->where('indiamartkey', 'tradindiakey')->update(['limit'=>$recordsCount + $dbLimit]);
               
                 echo "Data Inserted Successfully";
               }else{
                echo 'No Data Found';
                exit;
               }
               
            }else{
                echo 'Sorry! You are not authorized to view this.';
                exit;
            }
           
        } catch (\Exception $e) {   
            
            Log::build([
                'driver' => 'single',
                'path' => storage_path('logs/tradindia.log'),
            ])->info(["India Mart Log " => $e->getMessage()]);
            echo "Something went wrong";
        }
    }
}
