<?php

use App\Models\WashCategoryBodyType;
// 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 = "admin@autoclick.co.in";
    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.";  
}

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, '.', ',');

    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 sendWhatsapp($phone,$message){
    // echo "sendWhatsapp";exit;
        
    $sid = "ACdabf4a55beb849149560d4c9d5a763c8";
    $token = "75953403abd6fb6091d1741c037fcb29";
    $twilio = new Client($sid, $token);
    try{
        $message = $twilio->messages->create(
            "whatsapp:$phone", // to
            [
                "from" => "whatsapp:+14155238886",
                "body" => $message,
            ]
        );
    }
    catch(Exception $e) {

    }

}
