<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Lead;
use App\Models\Token;
use Facebook\Facebook;
use App\Models\Data;
use Log;
use DB; 
use Hash;
use Illuminate\Support\Facades\Response; 
class LeadController extends Controller
{
    public function createLead(Request $request)
    {
        try {
            $leadData = $request->all();
            $lead = Lead::create($leadData);
            return response()->json(['message' => 'Lead saved', 'lead' => $lead], 201);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error saving lead'], 500);
        }
    }

    public function getAllFacebookLead(Request $request)
    {
        try {
            $page = $request->query('page', 1);
            $limit = 20;
            $leads = Lead::skip(($page - 1) * $limit)->take($limit)->orderBy('id', 'desc')->get();
            #return json_decode($leads[0]['form_data'], true);
            $totalLeads = Lead::count();
            $totalPages = ceil($totalLeads / $limit);

            return response()->json([
                'leads' => $leads,
                'totalPages' => $totalPages,
                'totalLeads' => $totalLeads,
                'currentPage' => $page
            ]);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error retrieving leads'], 500);
        }
    }

    private function getAccessToken()
    {
        $tokenData = Token::first();
      
        if (!$tokenData) {
            throw new \Exception("No token found. Please initialize the token first.");
        }
        return $tokenData->token;
    }

    
    private function fetchFullLeadData($leadgenId)
    {
    $accessToken = $this->getAccessToken();
    $url = 'https://graph.facebook.com/v20.0/' . $leadgenId . '?fields=field_data&access_token=' . $accessToken;
    
    try {
        $response = \Http::get($url);
         //\Log::info($response);
          if ($response->successful()) {
            return $response->json()['field_data'] ?? [];
          // \Log::info($response);
         return $response;
        } else {
            Log::error('Error fetching lead data:', ['error' => $response->body()]);
            throw new \Exception("Error fetching lead data");
        }
    } catch (\Exception $e) {
        Log::error('Exception fetching lead data:', ['error' => $e->getMessage()]);
        throw new \Exception("Exception fetching lead data");
    }
    }

    public function webhook(Request $request)
    {
      
        $body = $request->all();
       
        
        if ($body['object'] === 'page') {
            
            foreach ($body['entry'] as $entry) {
                foreach ($entry['changes'] as $change) {
                    if ($change['field'] === 'leadgen') {
                        $leadgenId = $change['value']['leadgen_id'];
                        
                        $fullLeadData = $this->fetchFullLeadData($leadgenId);
                       // return $fullLeadData;
                        
                        $leadData = [
                            'platform' => 'Facebook',
                            'page_id' => $change['value']['page_id'],
                            'leadgen_id' => isset($change['value']['leadgen_id']) ? $change['value']['leadgen_id'] : 'NULL',
                            'form_id' => $change['value']['form_id'],
                           // 'created_at' => \Carbon\Carbon::createFromTimestamp($change['value']['created_time']),
                            'adgroup_id' => isset($change['value']['adgroup_id']) ? $change['value']['adgroup_id'] : 'NUll',
                            'ad_id' => isset($change['value']['ad_id']) ? $change['value']['ad_id'] : 'NULL',
                            'form_data' =>  json_encode($fullLeadData),
                        ];
                     
                        try {
                            Lead::create($leadData);
                           //  \Log::info(Lead::create($leadData));
                        } catch (\Exception $e) {
                            return response()->json(['error' => 'Error processing lead'], 500);
                        }
                    }
                }
            }
            return response()->json(['message' => 'EVENT_RECEIVED'], 200);
        } else {
            return response()->json(['error' => 'Event not from a page subscription'], 404);
        }
    }
     
    public function webhookPost(Request $request)
    {
        
                    $leadData = [
                        'platform' => 'Facebook',
                        'page_id' => "",
                        'leadgen_id' => "",
                        'form_id' => "",
                        //'created_at' => $request->created_at,
                        'adgroup_id' => "",
                        'ad_id' => "",
                        'form_data' => json_encode($request->form_data),
                    ];
        
                    try {
                        Lead::create($leadData);
                    } catch (\Exception $e) {
                        
                        return response()->json(['error' => 'Error processing lead'], 500);
                    }
                
        return response()->json(['message' => 'EVENT_RECEIVED'], 200);
        
    }
    
    public function SocialMediaLeads(){

        $data = Lead::orderBy('id', 'desc')->get();
        return view('smleads')->with([
            'data' =>$data
        ]);
    
    }
    public function WhatsaapLeads(){

        $data = Data::all();
        return view('waleads')->with([
            'data' =>$data
        ]);
    
    }
//website Lps data store
    public function websiteData(Request $request)
    {
        $data = new Lead();
        $data->patient_name = $request->patient_name;
        $data->patient_email = $request->patient_email;
        $data->patient_phone = $request->patient_phone;
        $data->reports = $request->reports;
        $data->subject = $request->subject;
        $data->platform = $request->platform;
        $data->status ='1';
        $data->save(); 
        // $newData = Data::create($request->all());
        // \Log::info($data);
        return response()->json(['data'=>$data], 200);
    }

    public function websiteDataList(){
        $json= [];
        $data = Lead::where('platform', '!=', 'Facebook')->orderBy('id', 'desc')->get();
        $json=['data'=>$data];
        return response()->json($json);
    }


    //  patient register to medflick 

    public function SMMedflickDataPost(){
        //medflick patient data insertion API

        $data = Lead::get('form_data');
        // return $data;
       // $json = json_decode($data, true);
        $dataArray = json_decode($data, true);

        // Loop through the array
        foreach ($dataArray as $entry) {
            if (!is_null($entry['form_data'])) {
            // Decode the JSON string
            $formData = json_decode($entry['form_data'], true);

            // Check for JSON errors
            if (json_last_error() === JSON_ERROR_NONE) {
            // Loop through the decoded data
            $name = '';
            $email = '';
            $phone = '';
            foreach ($formData as $field) {

                $jsondata=[];
                
                if($field['name']=='full_name'){
                $name = implode(", ", array_map('htmlspecialchars', $field['values']));
                }
                if($field['name']=='email'){
                    $email =  implode(", ", array_map('htmlspecialchars', $field['values']));
                }
                if($field['name']=='phone_number'){
                    $phone =  implode(", ", array_map('htmlspecialchars', $field['values']));
                }

                $jsondata=['name'=>$name, 'email'=>$email, 'phone'=>$phone, 'role'=>'patient', 'password'=>Hash::make($phone)];
                
                $curl = curl_init();
                curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://dev.medflick.com/api/free_consultants',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>$jsondata,
                CURLOPT_HTTPHEADER => array(
                'Cookie: XSRF-TOKEN=eyJpdiI6IjJLS3RZZExhOHppRXJUMDhpdnVzU1E9PSIsInZhbHVlIjoiMWliR05KY01MYVQreHZLeDh5MTI1Y0VPQjNISDdCbzF3aVlOcWFzMkJzZUFSQkNack5VU2VjdUFvUzBtc25hcGF6WGVhOGhzUzZGQnRieU43UzlTczRUZUNsQmFMTmFsR0xDcmgrcStqS2sya2VCQ1ovd0wzM1BlUjBUSkF5MEQiLCJtYWMiOiJmNjc2NmZhMmM2YWE4NjE5ZTExZjNjNzBlMjVlZTBkMzM4ODUxODMxNTdjOTA1ODIyNDExMmJhMjA3ZWVjZTVkIiwidGFnIjoiIn0%3D; medflick_session=eyJpdiI6InJrYkVCSERLYUZLaU1VeXAvalMwTHc9PSIsInZhbHVlIjoiVm9yUFZYVVo4aDkvbGVRSWR1cEQ0YnFOekVZNW1nc3lWSlFzSDJ3WXU5aVRCNEFma1Q2OFMzQU5DNXIxcHlzQ2FFd0RmOGM0UldVdlM5YTVPc0VsOFdkQzNmMmlBbzdTMU1JeDBUYkM2SHdLNmxxQlFvc2Vic2xhbkNJMnVGTXkiLCJtYWMiOiI1NGUxYzcyODBmYmY0ZDJjN2MyNzI2ZWI0YmRiNzQzNzAzMDViMDE4MzcxMzllYjExNGQzMDNhMjgzMmEzNDk0IiwidGFnIjoiIn0%3D'
                ),
                ));
                $response = curl_exec($curl);
                curl_close($curl);  

            }
            } else {
            echo "Error decoding JSON: " . json_last_error_msg() . "\n";
            }
            }  else {
        echo "Form data is null\n";
        }
        echo "\n";
        } 
        return response()->json( $response );
      
      //End patient data insertion
    }

//end patient register


    public function postDataMedflick(Request $request){
       
       $data = Lead::where('platform', '!=', 'Facebook')->orderBy('id', 'desc')->get();
           $jsondata = [];
            foreach ($data as $field) {

                $jsondata=['name'=>$field['patient_name'], 'email'=>$field['patient_email'], 'phone'=>$field['patient_phone'], 'role'=>'patient', 'password'=>Hash::make($field['patient_phone'])];
                $curl = curl_init();
                curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://dev.medflick.com/api/free_consultants',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>$jsondata,
                CURLOPT_HTTPHEADER => array(
                'Cookie: XSRF-TOKEN=eyJpdiI6IjJLS3RZZExhOHppRXJUMDhpdnVzU1E9PSIsInZhbHVlIjoiMWliR05KY01MYVQreHZLeDh5MTI1Y0VPQjNISDdCbzF3aVlOcWFzMkJzZUFSQkNack5VU2VjdUFvUzBtc25hcGF6WGVhOGhzUzZGQnRieU43UzlTczRUZUNsQmFMTmFsR0xDcmgrcStqS2sya2VCQ1ovd0wzM1BlUjBUSkF5MEQiLCJtYWMiOiJmNjc2NmZhMmM2YWE4NjE5ZTExZjNjNzBlMjVlZTBkMzM4ODUxODMxNTdjOTA1ODIyNDExMmJhMjA3ZWVjZTVkIiwidGFnIjoiIn0%3D; medflick_session=eyJpdiI6InJrYkVCSERLYUZLaU1VeXAvalMwTHc9PSIsInZhbHVlIjoiVm9yUFZYVVo4aDkvbGVRSWR1cEQ0YnFOekVZNW1nc3lWSlFzSDJ3WXU5aVRCNEFma1Q2OFMzQU5DNXIxcHlzQ2FFd0RmOGM0UldVdlM5YTVPc0VsOFdkQzNmMmlBbzdTMU1JeDBUYkM2SHdLNmxxQlFvc2Vic2xhbkNJMnVGTXkiLCJtYWMiOiI1NGUxYzcyODBmYmY0ZDJjN2MyNzI2ZWI0YmRiNzQzNzAzMDViMDE4MzcxMzllYjExNGQzMDNhMjgzMmEzNDk0IiwidGFnIjoiIn0%3D'
                ),
                ));
                $response = curl_exec($curl);
                curl_close($curl);  
             }
             return response()->json(['data'=>$jsondata, 'message'=>'Data inserted']);
    }
}