<?php
// require_once 'php-oauth2-example/vendor/autoload.php';
require_once '../php-oauth2-example/vendor/autoload.php';

use App\Models\WashCategoryBodyType;
use App\Models\BusinessHours;
use App\Models\Rating;
use App\Models\Review;
use App\Models\FcmAuthToken;
// use Mail;
use Twilio\Rest\Client;

if (!function_exists('csvDownlaod')) {
    function csvDownlaod($csv_array, $filename)
    {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        // $user_CSV[0] = array('first_name', 'last_name', 'age');

        // // very simple to increment with i++ if looping through a database result
        // $user_CSV[1] = array('Quentin,sss', 'Del Viento', 34);
        // $user_CSV[2] = array('Antoine', 'Del Torro', 55);
        // $user_CSV[3] = array('Arthur', 'Vincente', 15);

        $fp = fopen('php://output', 'wb');
        foreach ($csv_array as $line) {
            // though CSV stands for "comma separated value"
            // in many countries (including France) separator is ";"
            fputcsv($fp, $line, ',');
        }
        fclose($fp);
    }
}
if (!function_exists('excludeKeysFromArray')) {
    function excludeKeysFromArray($array, $keysToExclude)
    {
        return array_map(function ($subArray) use ($keysToExclude) {
            foreach ($keysToExclude as $key) {
                unset($subArray[$key]);
            }
            return $subArray;
        }, $array);
    }
}


function getBodyTypePrice($wash_category_id, $body_type_id)
{
    $arr = WashCategoryBodyType::where('wash_category_id', "=", $wash_category_id)->where('body_type_id', "=", $body_type_id)->select('price')->first();
    if ($arr != '') {
        $value = $arr->price;
    } else {
        $value = '';
    }

    return $value;
}

function getBodyTypeDuration($wash_category_id, $body_type_id)
{
    $arr = WashCategoryBodyType::where('wash_category_id', "=", $wash_category_id)->where('body_type_id', "=", $body_type_id)->select('duration')->first();
    if ($arr != '') {
        $value = $arr->duration;
    } else {
        $value = '';
    }
    return $value;
}

/*function sendMail ($receiver_info, $content, $subject, $sender_info=null) {
    $sender_name="Autoclick";
    $sender_email="admin@gmail.com";
    if ($sender_info!=null) {
       $sender_name=$sender_info[0];
       $sender_email=$sender_info[1]; 
    }
    
    $receiver_name=$receiver_info[0];
    $receiver_email=$receiver_info[1];
   
    $email_template=file_get_contents(public_path('email_template/email-template.html'));
    $email_template=str_replace(array('##receiver_name##','##mail_content##'),array($receiver_name, $content), $email_template);
       

    try {
        Mail::send([],[], function ($message) use($sender_name, $sender_email, $receiver_name, $receiver_email, $subject, $email_template) {
          $message
            // ->from($sender_email,$sender_name)
            ->to($receiver_email,$receiver_name)
            // ->bcc("testmail@yopmail.com","Admin")
            ->html($email_template )
            ->subject($subject);
        });
        return true;

        // Mail::send('email.api.register', ['user_details' => $user_details, 'ticket_details' => $data], function ($message) use ($parent_email) {
        //     $message->to($parent_email);
        //     $message->subject('Savvy Parent - Student SOS');
        // });
    }

    //catch exception
    catch(Exception $e) {
      echo 'Message: ' .$e->getMessage();
      return false;
    }
}*/

function sendMail($receiver_info, $content, $subject, $sender_info = null)
{
    $sender_name = "Autoclick";
    $sender_email = "support@autoclick.co.za";
    if ($sender_info != null) {
        $sender_name = $sender_info[0];
        $sender_email = $sender_info[1];
    }

    $receiver_name = $receiver_info[0];
    $receiver_email = $receiver_info[1];

    // $to = $receiver_email;
    // $subject = $subject;
    // $message = $content;
    // $from = $sender_email;
    // $headers = "From: $from";  
    /*$headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $from";*/
    // mail($to, $subject, $message, $headers);
    // echo "Mail Sent.";  

    try {
        Mail::send([],[], function ($message) use($sender_name, $sender_email, $receiver_name, $receiver_email, $subject, $content) {
          $message
            ->from($sender_email,$sender_name)
            ->to($receiver_email,$receiver_name)
            // ->bcc("tamashree@karmicksolutions.com","Admin")
            ->html($content )
            ->subject($subject);
        });
        return true;

        // Mail::send('email.api.register', ['user_details' => $user_details, 'ticket_details' => $data], function ($message) use ($parent_email) {
        //     $message->to($parent_email);
        //     $message->subject('Savvy Parent - Student SOS');
        // });
    }

    //catch exception
    catch(Exception $e) {
      echo 'Message: ' .$e->getMessage();
      return false;
    }
}

function generateUniqueNumberCo()
{

    $str_result = '0123456789';
    $middle = substr(str_shuffle($str_result), 0, 6);
    $value = 'ACCO' . $middle . 'C';

    return $value;
}

function generateUniqueNumberCWO()
{

    $str_result = '0123456789';
    $middle = substr(str_shuffle($str_result), 0, 6);
    $value = 'ACWO' . $middle . 'P';

    return $value;
}

function encryptor($action, $string)
{
    $output = false;

    $encrypt_method = "AES-256-CBC";
    //pls set your unique hashing key
    $secret_key = 'thegame';
    $secret_iv = 'thisisasalt';

    // hash
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    //do the encyption given text/string/number
    if ($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } elseif ($action == 'decrypt') {
        //decrypt the given text/string/number
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

function encodeC($data)
{

    $data = encryptor('encrypt', $data);
    return $data;
}

function decodeC($data)
{

    $data = encryptor('decrypt', $data);
    return $data;
}

function generateNumericOTP($n)
{
    // all numeric digits
    $generator = "1357902468";
    $result = "";
    for ($i = 1; $i <= $n; $i++) {
        $result .= substr($generator, (rand() % (strlen($generator))), 1);
    }
    // Return result
    return $result;
}

function getDateDiff($start_date, $start_time, $end_date, $end_time)
{

    $date1 = new DateTime($start_date . $start_time);
    $date2 = new DateTime($end_date . $end_time);
    $interval = $date1->diff($date2);

    $elapsed = $interval->format('%h hrs %i min');
    return $elapsed;
}

function sendWhatsappText($mobile)
{
    $data = [
        'api_key' => 'Your-Api-Key',
        'to' => $mobile,
    ];
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://app.getgabs.com/whatsappbusinesstestcases/send-text-message',
        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 => json_encode($data),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;
}

function sendWhatsappOtp($mobile, $otp)
{
    $data = [
        'api_key' => 'Your-Api-Key',
        'to' => $mobile,
        'otp' => $otp,
    ];
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://app.getgabs.com/whatsappbusinesstestcases/send-authentication-message',
        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 => json_encode($data),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;
}

function formatCurrency($amount)
{

    // $formattedAmount = 'R' . number_format($amount, 2, '.', ',');
    $formattedAmount = number_format($amount, 2, '.', ',');

    return $formattedAmount;
}

function getCleaners($wash_id)
{
    // $wash_id = 75;
    $cleaners = DB::table('cleaner_washes')->select('cleaner_masters.name')->where('wash_id', $wash_id)
        ->join('wash_details', 'cleaner_washes.wash_id', 'wash_details.id')
        ->join('cleaner_masters', 'cleaner_washes.cleaner_id', 'cleaner_masters.id')
        ->get()->toArray();
    // dd($cleaners);
    $cleaner_names = '-';
    if (!empty($cleaners)) {
        $names = array_map(function ($item) {
            return $item->name;
        }, $cleaners);
        $cleaner_names = implode(', ', $names);
    }

    return $cleaner_names;
}

function getExtra($wash_id)
{
    // $wash_id = 75;
    $extras = DB::table('optional_extras')->select('optional_extras.optional_extra', 'optional_extras.price')->where('optional_extras.wash_id', $wash_id)
        ->join('wash_details', 'optional_extras.wash_id', 'wash_details.id')
        ->get()->toArray();
    // dd($extras);
    $optional_extra = '';
    if (!empty($extras)) {
        $names = array_map(function ($item) {
            return $item->optional_extra;
        }, $extras);
        $optional_extra = implode(', ', $names);
    }

    return $optional_extra;
}


function sendWhatsapp($phone,$message_arr){
    // echo "sendWhatsapp";exit;
        
    $sid = "ACdabf4a55beb849149560d4c9d5a763c8";
    $token = "75953403abd6fb6091d1741c037fcb29";
    $twilio = new Client($sid, $token);
    $message_text = "";
    if(count($message_arr) == 2){
        $message_text = "Your car ".$message_arr[0]." is ready for collection at ".$message_arr[1]." Thank you! Regards, AUTOCLICK www.autoclickcarwashapp.com info@autoclick.co.za";
    }else{
        $message_text = "Hi ".$message_arr[0].", Your car ".$message_arr[1]." is in the queue at ".$message_arr[2]." and it will not be long. Your OTP to collect is  ".$message_arr[3].". Regards, AUTOCLICK  www.autoclickcarwashapp.com info@autoclick.co.za";
    }
    
    try{
        $message = $twilio->messages->create(
            "whatsapp:$phone", // to
            [
                "from" => "whatsapp:+27762933969",
                "body" => $message_text,
            ]
        );
    }
    catch(Exception $e) {

    }

}


function sendWhatsappCompletedOtp($phone,$message_arr){
    // echo "sendWhatsappCompletedOtp";exit;
    $sid = "ACdabf4a55beb849149560d4c9d5a763c8";
    $token = "75953403abd6fb6091d1741c037fcb29";
    $twilio = new Client($sid, $token);
    // $data = array(
    //     'name'  =>  "Supratim",
    //     'car'   =>  "Maruti",
    //     'company'   =>  "Autoclick co",
    //     'date'  =>  "05-07-2024",
    //     'amount'=>  "$1",
    //     'payment_type'  =>  "cash",
    //     'otp'   => "4569"
    // );
    $data = array(
        'name'  =>  $message_arr[0],
        'car'   =>  $message_arr[1],
        'company'   =>  $message_arr[2],
        'date'  =>  $message_arr[3],
        'amount'=>  'R' . $message_arr[4],
        'payment_type'  =>  $message_arr[5],
        'otp'   => $message_arr[6],
        'cwo-contact-number'   => $message_arr[7]
    );
    // echo $phone;exit;
    // print_r($data);exit;
    try{
        $message = $twilio->messages->create(
            "whatsapp:$phone", //+27769515554", // to
            [
                "from" => "MG30b4c84929f2b9513be21a7da3f0f207",
                // "ContentSid" => "HXf1bd6a61364f60f7252f1bb279c8de5a",
                // "ContentSid" => "HXacff51e779eaf50470f711412e61f620",
                // "ContentSid" => "HX3144986a907931ee30eea4ffe37b8530",
                // "ContentSid" => "HX8106b116f0f0872c3c6310b5917bc140",
                // "ContentSid" => "HX20e735cfe4de6929361eeb13bf58cfde",
                // "ContentSid" => "HX7d96fe2c01650c52a9ab6df0017faf5f",
                "ContentSid" => "HX87c9260d6a4513f6d17e7ad6e04b00f7",
                // "ContentVariables" => json_encode(["1"=>$data["name"], "2"=>$data["car"], "3"=>$data["company"], "4"=>$data["date"], "5"=>$data["amount"], "6"=>$data["payment_type"], "7"=>$data["otp"], "8"=>$data["company"], "9"=>$data["cwo-contact-number"]])
                "ContentVariables" => json_encode(["1"=>$data["name"], "2"=>$data["car"], "3"=>$data["company"], "4"=>$data["date"], "5"=>$data["amount"], "6"=>$data["otp"], "7"=>$data["company"], "8"=>$data["cwo-contact-number"]])
            ]
        );
        // print_r($message);exit;
    }
    catch(Exception $e) {
        // print_r($e);exit;
    }
}

function sendWhatsappInQueueOtp($phone,$message_arr){
    // echo "sendWhatsappCompletedOtp";exit;
    $sid = "ACdabf4a55beb849149560d4c9d5a763c8";
    $token = "75953403abd6fb6091d1741c037fcb29";
    $twilio = new Client($sid, $token);
    // $data = array(
    //     'name'	=>	"Supratim",
    //     'car'	=>	"Maruti",
    //     'company'	=>	"Autoclick co",
    //     'otp'	=> "4569"
    // );
    $data = array(
        'name'  =>  $message_arr[0],
        'car'   =>  $message_arr[1],
        'company'   =>  $message_arr[2],
        'otp'  =>  $message_arr[3],
        'cwo-contact-number'   => $message_arr[4]
    );
    // echo $phone;exit;
    // print_r($data);exit;
    try{
        $message = $twilio->messages->create(
            "whatsapp:$phone", //+27769515554", // to
            [
                "from" => "MG30b4c84929f2b9513be21a7da3f0f207",
                // "ContentSid" => "HXeaa9ce3a82f83f615398840fcded268f",
                // "ContentSid" => "HX95220dae42b3b367438ac27f35cb1744",
                // "ContentSid" => "HXd3ca3cb3401e9ca70b47a78b9b629a7f",
                // "ContentSid" => "HX9c17e10eb433a2b515023e003a6dce5c",
                "ContentSid" => "HXdf56735ec884122ba7b7e76c7fa00ead",
                "ContentVariables" => json_encode(["1"=>$data["name"], "2"=>$data["car"], "3"=>$data["company"], "4"=>$data["otp"], "5"=>$data["company"], "6"=>$data["cwo-contact-number"]])
            ]
        );
        // print_r($message);exit;
    }
    catch(Exception $e) {
        // print_r($e);exit;
    }
}


function getDateDiffBay($start_time, $end_time)
{

    $date1 = new DateTime($start_time);
    $date2 = new DateTime($end_time);
    $interval = $date1->diff($date2);

    $elapsed = $interval->format('%h hrs %i min %s sec');
    return $elapsed;
}


function getWashTypes($wash_id)
{
    $washTypes = DB::table('wash_type_to_washes')->select('wash_categories.wash_name', 'wash_type_to_washes.price')
        ->join('wash_details', 'wash_type_to_washes.wash_id', 'wash_details.id')
        ->join('wash_categories', 'wash_type_to_washes.wash_type_id', 'wash_categories.id')
        ->where('wash_type_to_washes.wash_id', $wash_id)
        ->get()
        ->toArray();
    // dd($washTypes);
    $wash_category_names = ' ';
    if (!empty($washTypes)) {
        $names = array_map(function ($item) {
            return $item->wash_name . '('. $item->price . ')';
        }, $washTypes);
        $wash_category_names = implode(', ', $names);
    }

    return $wash_category_names;
}

function getSingleWashTypeName($wash_type_id) {
    $washcategory = DB::table('wash_categories')->select('wash_name')
        ->where('id', $wash_type_id)
        ->first();
    return $washcategory->wash_name;    
}

function getLowestPrice($wash_category_id, $body_type_id) {
    // $initial = 0;
    $lowest_price = '0';
    // $lowest_price_wash_category_id = 0;
    // echo "<pre>"; print_r($wash_category_id);exit;
    if (count($wash_category_id) > 0) {
        for ($i = 0; $i < count($wash_category_id); $i++) {
            $getPrice = WashCategoryBodyType::where('wash_category_id', $wash_category_id[$i])->where('body_type_id', $body_type_id)->first();
            $price = $getPrice->price;
            if($i == 0) {
                $lowest_price = $price;
                $lowest_price_wash_category_id = $wash_category_id[$i];
            }
            // echo $getPrice->price . "<br>";
            if($price < $lowest_price) {
                $lowest_price = $price;
                $lowest_price_wash_category_id = $wash_category_id[$i];
                // echo $wash_category_id[$i];
            }
            // echo $wash_category_id[$i] . ' - ' . $price . ' - ' . $lowest_price . ' - ' . $lowest_price_wash_category_id . "<br>";
            // echo $lowest_price;exit;
        }
        // echo $lowest_price;exit;
        // echo $lowest_price_wash_category_id;exit;
        // exit;
    }
    return $lowest_price_wash_category_id;    
}

function getLatLongFromAddress($address) {
    // Google Maps API Key 
    $GOOGLE_API_KEY = 'AIzaSyDQw4gzmBioBV93OSqhD2PP6LAOcm5_MXc'; 
     
    // Formatted address 
    $formatted_address = str_replace(' ', '+', $address); 
     
    // Get geo data from Google Maps API by address 
    $geocodeFromAddr = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$formatted_address}&key={$GOOGLE_API_KEY}"); 
     
    // Decode JSON data returned by API 
    $apiResponse = json_decode($geocodeFromAddr); 
    // print_r($apiResponse);exit;
     
    // Retrieve latitude and longitude from API data 
    $latitude  = $apiResponse->results[0]->geometry->location->lat;  
    $longitude = $apiResponse->results[0]->geometry->location->lng; 

    // Render the latitude and longitude of the given address 
    $data = array(
        'lat' => $latitude,
        'long' => $longitude
    );
    return $data;
}

function getFromHours($cwo_id, $day)
{
    $arr = BusinessHours::where('cwo_id', "=", $cwo_id)->where('day', "=", $day)->select('from_hours')->first();
    if ($arr != '') {
        $value = $arr->from_hours;
    } else {
        $value = NUll;
    }

    return $value;
}

function getToHours($cwo_id, $day)
{
    $arr = BusinessHours::where('cwo_id', "=", $cwo_id)->where('day', "=", $day)->select('to_hours')->first();
    if ($arr != '') {
        $value = $arr->to_hours;
    } else {
        $value = NUll;
    }

    return $value;
}

function getOpenStatus($cwo_id, $day)
{
    $arr = BusinessHours::where('cwo_id', "=", $cwo_id)->where('day', "=", $day)->select('status')->first();
    if ($arr != '') {
        $value = $arr->status;
    } else {
        $value = NUll;
    }

    return $value;
}

function getCwoRating($cwo_id)
{
    $arr = Rating::select(DB::raw('SUM(rating) as total_rating'), DB::raw('Count(rating) as total_count'))->where('cwo_id', "=", $cwo_id)->get();
    // echo "<pre>";print_r($arr->toArray());exit;
    if ($arr != '') {
        // echo $arr[0]->total_rating . '-' . $arr[0]->total_count;exit;
        if($arr[0]->total_count > 0){
            $value = $arr[0]->total_rating / $arr[0]->total_count;
            $value = number_format($value, 1, '.', ',');
        } else {
            $value = '';
        }
    } else {
        $value = '';
    }

    return $value;
}

function getCwoReviewCount($cwo_id)
{
    $arr = Review::select(DB::raw('Count(id) as total_count'))->where('cwo_id', "=", $cwo_id)->where('is_cwo_user', 0)->get();
    // echo "<pre>";print_r($arr->toArray());exit;
    if ($arr != '') {
        $value = $arr[0]->total_count;
    } else {
        $value = 0;
    }

    return $value;
}

function generateFcmAuthToken() {
    $client = new Google\Client();
    // $client->setAuthConfig("public/autoclick-car-wash-firebase-adminsdk-manz1-718eba8255.json");
    $client->setAuthConfig("autoclick-car-wash-firebase-adminsdk-manz1-718eba8255.json");
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Fetch the access token
    $tokenArray = $client->fetchAccessTokenWithAssertion();
    // print_r($tokenArray);
    // [expires_in] => 3599 means 3599 second   
    
    if (isset($tokenArray['access_token'])) {
        $val=[
        "access_token"=>$tokenArray['access_token'],
        "expires_in"=>$tokenArray['expires_in']
    ];
        $val=json_encode($val);
        return $val;
    } else {
        throw new Exception('Could not obtain the access token.');
    }
       
}

function fcmAuthToken() {
    $current_date=date("Y-m-d H:i:s");
    $current_date_to_time=strtotime($current_date);
    // add 5 minute
    $expiry_date=date("Y-m-d H:i:s", ($current_date_to_time+300));
    $check_token=FcmAuthToken::where("type","initial")->where("expiry_date", ">", $expiry_date)->count();
    if($check_token == 0) {
        $token_details=generateFcmAuthToken();
        $token_details=json_decode($token_details);
        $access_token=$token_details->access_token;
        $expires_in=$token_details->expires_in;
        
        $new_expiry_date=date("Y-m-d H:i:s", ($current_date_to_time+$expires_in));
        
        $token_update=FcmAuthToken::where("type","initial")->first();
        $token_update->value=$access_token;
        $token_update->expiry_date=$new_expiry_date;
        $token_update->updated_at=$current_date;
        $token_update->save();
        
    } else {
        $token_details=FcmAuthToken::where("type","initial")->first();
        $access_token=$token_details->value;
    }
    
    return $access_token;
}

function sendFcmNotification($fcm_token, $notification_title, $notification_body, $data=NULL) {
   $access_token=fcmAuthToken();
   // $access_token="ya29.c.c0ASRK0GbxSM57t7tjj0RcwA7IU-ldAMjmqB2LuC7tAUFU3d-QmgMR9kP_IlKWf8_qzgojjZ3Ucz5tNvUXNyjwHA1d2OwwHfIbV9gBpsLGQkGAjEABYdhfg5FulxWoqmzQpmRvdARYdo7LsxGiNmpGkyFRhxth9_MlW1WlIjEPA4a1OToMmySO0zNOIvVn2mOaufZxtROnRr-ML4oYGV3nUqGJE9HezFm7tLHoPSXK0Ehk2oUT2CU0G8W0b1xKtKwpHPz7YRjg8qyrybepsEWPuOyWD4v8x1p6DC43w4JtrJceusGivdkiNirCNTquFU_rp0qyITsNvNEvKkbJOqcGcKxsKI8faIT7eZyiSmjZkLhG9CXn98iFpNRFG385AnogjcMV6q6al9jce22zlmgV1qhdk6vsMO89Ssbr-uI-0xObrUtbUhpjI72Vk-57iUIbfpyzrfO9ojvcM48Uc3qjvhrf7R9nin3QpVOyIlv68V_XFy6mpZ8nQc5gjip2dYu0ehZtdvIcfrX__hcU6VeV0pU30hmgU3fqMuY3deuzIQwfUucvYnw580x9boF0wuR6gYgYhs7aZ1_p2wVZUzMR0VX0U13Zz_dhlbZWvbzuMxUnxjxUftQ3WO-eczvBBaOpa6rMiBtV4Z_Rle-0on2904jq-OkQX6c6wUwY7kf95cOy-pmq5v2hXZ550ihQneuF5YBwiaqUluoM35_dOO1osqni8cSm3moh9_isqhVdxF_aYyR5vbh_WwUZxV58miwrh5mSMM9Y_dV3VV6uVF1ZS6a6626X0reZi_lIjZMwXVbcQ_p9IMjStQWor88s30nWq0Rsk9e_7gQeFdh85npZ2eoRJVJ3e10qSbQMicsJjJfonYYn_UI_eQt9WBSx8-mlnsoWqnS7QmzutIRIojorwaw56iI3b-izWxI0SJvRlx-b61dUwjF2MJorOqoztOo2M3MWYrjV1qhVfdW1l0Y4kr4j271SuRBSBMOS6-wspXbbg-tqxX75rS0";

   $url="https://fcm.googleapis.com/v1/projects/autoclick-car-wash/messages:send";
   
   $message_fields=[
        "message"=>[
            "token"=>$fcm_token,
            "notification" => [
                "title" => $notification_title, //Any value
                "body" => $notification_body, //Any value
                
                ],
            
           
            /*
            "data" => [
        "request_type" => $request_type
    ],
            */
            
            // "android" =>[
            //     "priority" => "high",
            //     "notification"=>[
            //         "click_action"=> "SplashActivity",
            //         "icon" => "logo_small_kids"
            //     ]
            // ],
            // "apns"=>[
            //     "headers"=>[
            //         "apns-priority"=> "5"
            //     ]
            // ],
            // "webpush"=>[
            //     "headers"=>[
            //         "Urgency"=> "high"
            //     ]
            // ]
        ]
    ];
   
    if($data!==null && count($data)>0) {
        $message_fields['message']['data']=$data;
    }
    //echo "H1234<pre>";echo(json_encode($message_fields));
  
   //echo json_encode($message_fields);
    $headers = [
        'Authorization: Bearer ' . $access_token,
        'Content-Type: application/json'
    ];
        
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message_fields));
    $result = curl_exec($ch);
        
        
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);

    $result = json_decode($result);
    // echo "<pre>";
    // print_r($result);
}





