<?php
use Illuminate\Support\Facades\Storage;
use App\Models\WhatsappTracker;
use App\Models\LeadManagement;
if (!function_exists('check_file_exist')) {
    function check_file_exist($filePath)
    {
        return Storage::disk('s3')->exists($filePath);
    }
}
function send_whatsapp($template = null, $options,$marketing_status = 0)
{

    if ($template == null || $template == '') {
        return ['status' => 0, 'msg' => 'Template name is required!'];
    } else if (!isset($options['siteName']) || $options['siteName'] == '') {
        return ['status' => 0, 'msg' => 'siteName is required!'];
    } else if (!isset($options['sendTo']) || $options['sendTo'] == '') {
        return ['status' => 0, 'msg' => 'sendTo is required!'];
    }

    $webInfo = [
        'GAH' => ['siteFullName' => 'Global Assignment help', 'siteEmail' => 'help@globalassignmenthelp.com'],
        'GAH_AU' => ['siteFullName' => 'Global Assignment help Australia', 'siteEmail' => 'help@globalassignmenthelp.com.au'],
        'IAH' => ['siteFullName' => 'Instant Assignment help', 'siteEmail' => 'help@instantassignmenthelp.com'],
        'IAH_AU' => ['siteFullName' => 'Instant Assignment help Australia', 'siteEmail' => 'help@instantassignmenthelp.com.au'],
        'AP' => ['siteFullName' => 'Assignment Prime', 'siteEmail' => 'help@assignmentprime.com'],
        'AD' => ['siteFullName' => 'Assignment Desk', 'siteEmail' => 'help@assignmentdesk.co.uk'],
    ];


    $siteName = $options['siteName'];
    $options['siteFullName'] = $webInfo[$siteName]['siteFullName'];
    $options['siteEmail'] = $webInfo[$siteName]['siteEmail'];

    $options['sendTo'] = $sendTo = trim(str_replace(['-','+'],'',$options['sendTo']));
    $number = strval($sendTo);
    $firstDigit = $number[0];
    $integrationIds = [
        'GAH' => '64be45e42201a59655f99f78',
        'IAH' => '64be50233d7724990749d181',
        'IAH_AU' => '64be502f6eb68b7ac8d1bc87',
        'AP' => '64c39f4c08430a97494c91c6',
        'GAH_AU' => '64be4aee8973887c1225b2f8',
        'AD' => '64c3a150ed18577054311eb3',
        // 'new' => '60f29b0940241100d48b27d0'
    ];

    $nameSpaces = [
        'GAH' => '38b90dea_6936_4c42_9930_9bc661d37719',
        'GAH_AU' => '38b90dea_6936_4c42_9930_9bc661d37719',
        'IAH' => '38b90dea_6936_4c42_9930_9bc661d37719',
        'IAH_AU' => '38b90dea_6936_4c42_9930_9bc661d37719',
        'AP' => '38b90dea_6936_4c42_9930_9bc661d37719',
        'AD' => '38b90dea_6936_4c42_9930_9bc661d37719'
    ];

    $templateName = [
        'GAH' => [
            'register' => 'register_with_300_gah',
            'quotation' => 'quotation',
            'quotation_maltipale' => 'gah_multi_quotation',
            'payment_confirmation' => 'gah_payment_confirmation_new',
            'payment_decline' => 'gah_payment_failure',
            'delivery' => 'gah_delivery_notification',
            'clarification' => 'gah_clarification',
            'payment_reminder' => 'gah_payment_reminder',
            'partial_payment' => 'gah_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_gah',
            'send_password' => 'password_gah', 
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_gah',
            'numberchange' => 'numberchangegah3',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'registration_tool' => 'registration_tool_gah_01',
            'wallet_update' => "wallet_update_gah",
            'registration_blog' => 'registration_blog_gah',
            'registration_sample' => 'registration_sample_gah',
            'plagiarism_register' => 'pagiarism_tool_registration_gah',
            'essay_register'=> 'essay_typer_registration',
        ],
        'IAH' => [
            'register' => 'register_with_300_iah',
            'quotation' => 'quotation_iah',
            'quotation_maltipale' => 'iah_multi_quotation',
            'payment_confirmation' => 'iah_payment_confirmation_new',
            'payment_decline' => 'iah_payment_failure',
            'delivery' => 'iah_delivery_notification',
            'clarification' => 'iah_clarification',
            'payment_reminder' => 'iah_payment_reminder',
            'partial_payment' => 'iah_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_iahnew',
            'send_password' => 'password_iah',
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_iah1',
            'numberchange' => 'numberchangeiah4',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'wallet_update' => "wallet_update_iah",
            'registration_tool' => 'registration_tool_iah',
            'registration_blog' => 'registration_blog_iah_01',
            'registration_sample' => 'registration_sample_iah',
            'plagiarism_register' => 'pagiarism_tool_registration_iah',
            'essay_register' => 'essay_typer_registration_iah',
        ],
        'IAH_AU' => [
            'register' => 'register_with_300_iah_au',
            'quotation' => 'quotation_iah_au',
            'quotation_maltipale' => 'iahau_multi_quotation',
            'payment_confirmation' => 'iahau_payment_confirmation',
            'payment_decline' => 'iahau_payment_failure',
            'delivery' => 'iahau_delivery_notification',
            'clarification' => 'iahau_clarification',
            'payment_reminder' => 'iahau_payment_reminder',
            'partial_payment' => 'iahau_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_iahaunew',
            'send_password' => 'password_iah_au', 
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_iahau1',
            'notification' => 'bahhhhaaaccac',
            'numberchange' => 'numberchangeiahau3',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'wallet_update' => "wallet_update_iah_au",
            'registration_tool' => 'registration_tool_iah_au',
            'registration_blog' => 'registration_blog_iah_au',
            'registration_sample' => 'registration_sample_iah_au',
            'plagiarism_register' => 'pagiarism_tool_registration_iah_au',
            'essay_register'=> 'essay_typer_registration_iah_au',
        ],
        'GAH_AU' => [
            'register' => 'register_with_300_gah_au',
            'quotation' => 'quotation_gah',
            'quotation_maltipale' => 'gahau_multi_quotation',
            'payment_confirmation' => 'gahau_payment_confirmation',
            'payment_decline' => 'gahau_payment_failure',
            'delivery' => 'gahau_delivery_notification',
            'clarification' => 'gahau_clarification',
            'payment_reminder' => 'gah_payment_reminder',
            'partial_payment' => 'gahau_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_gahaunew',
            'send_password' => 'password_gah_au',
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_gahau1',
            'numberchange' => 'numberchangegahau3',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'wallet_update' => "wallet_update_gah_au",
            'registration_tool' => 'registration_tool_gah_au',
            'registration_blog' => 'registration_blog_gah_au_01',
            'registration_sample' => 'registration_sample_gah_au',
            'plagiarism_register' => 'pagiarism_tool_registration_gah_au',
            'essay_register'=> 'essay_typer_registration_gah_au',
        ], 
        'AP' => [
            'register' => 'register_with_300_ap',
            'quotation' => 'quotation_ap',
            'quotation_maltipale' => 'ap_multi_quotation',
            'payment_confirmation' => 'ap_payment_confirmation',
            'payment_decline' => 'ap_payment_failure',
            'delivery' => 'ap_delivery_notification',
            'clarification' => 'ap_clarification',
            'payment_reminder' => 'ap_payment_reminder',
            'partial_payment' => 'ap_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_apneww',
            'send_password' => 'password_ap',
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_ap2',
            'numberchange' => 'numberchangeap3',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'wallet_update' => "wallet_update_ap",
            'registration_tool' => 'registration_tool_ap',
            'registration_blog' => 'registration_blog_ap',
            'registration_sample' => 'registration_sample_ap',
            'plagiarism_register' => 'pagiarism_tool_registration_ap',
            'essay_register'=> 'essay_typer_registration_ap',
        ], 
        'AD' => [
            'register' => 'register_with_300_ad',
            'quotation' => 'quotation_ad',
            'quotation_maltipale' => 'ad_multi_quotation',
            'payment_confirmation' => 'ad_payment_confirmation',
            'payment_decline' => 'ad_payment_failure',
            'delivery' => 'ad_delivery_notification',
            'clarification' => 'ad_clarification',
            'payment_reminder' => 'ad_payment_reminder',
            'partial_payment' => 'ad_partial_payment',
            'custom' => 'custom',
            'lead_followup' => 'lead_followup_adnew',
            'send_password' => 'password_ad',
            'file_delivery' => 'delivery_url_04',
            'image_code' => 'image_code_ad1',
            'numberchange' => 'numberchangead3',
            'web_whatapp' => 'web_whatapp',
            'download_essay' => 'download_essay',
            'wallet_update' => "wallet_update_ad",
            'registration_tool' => 'registration_tool_ad',
            'registration_blog' => 'registration_blog_ad_01',
            'registration_sample' => 'registration_sample_ad',
            'plagiarism_register' => 'pagiarism_tool_registration_ad',
            'essay_register'=> 'essay_typer_registration_ap',
            'ad_blog_page'=> 'ad_blog_page',
            
        ],
    ];

    $wp_tracking_code = time();

    if ($marketing_status == 1) {
        $integrationId = $integrationIds['marketing'][$siteName];
        $nameSpace = $nameSpaces['marketing'][$siteName];
    } elseif ($firstDigit == 1 && isset($integrationIds['USA'][$siteName])) {
        $integrationId = $integrationIds['USA'][$siteName];
        $nameSpace = $nameSpaces[$siteName];
    } else {
        $integrationId = $integrationIds[$siteName];
        $nameSpace = $nameSpaces[$siteName];
    }
    
    $templateNameFinal = $templateName[$siteName][$template];
    
    // Get template data (assume this is a method in the same controller or service)
    $templateData = getWhatsappTemplate($template, $options);
    
    // Build components
    $components = [];
    
    if (!empty($templateData['bodyData'])) {
        $components[] = [
            'type' => 'body',
            'parameters' => $templateData['bodyData'],
        ];
    }
    
    if (!empty($templateData['btnData'])) {
        $components[] = [
            'type' => 'button',
            'sub_type' => 'url',
            'index' => '0',
            'parameters' => $templateData['btnData'],
        ];
    }
    
    if (!empty($options['img'])) {
        $components[] = [
            'type' => 'header',
            'parameters' => [
                [
                    'type' => 'image',
                    'image' => [
                        'link' => $options['img']
                        // 'filename' => $options['siteFullName']
                    ]
                ]
            ]
        ];
    }
    
    // Build final payload
    $data = [
        'destination' => [
            'integrationId' => $integrationId,
            'destinationId' => $sendTo,
        ],
        'author' => [
            'role' => 'appMaker',
        ],
        'messageSchema' => 'whatsapp',
        'message' => [
            'type' => 'template',
            'template' => [
                'namespace' => $nameSpace,
                'name' => $templateNameFinal,
                'language' => [
                    'policy' => 'deterministic',
                    'code' => 'en',
                ],
                'components' => $components
            ],
        ],
    ];
   
   
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.smooch.io/v1.1/apps/64afffb12ced8ec77fccb223/notifications');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_USERPWD, 'app_6502a5d16040eb7f1104c650' . ':' . 'XkOhKaSHxH2yAbY3vx6ASsa6ExmJTMm0sbsysbDRhCOk5SSkRKDCqa0J_kehDsMniaFUag73sgXtkp7o6c1eiQ');

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
   
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
        return false;
    }
    $result = json_decode($result,1);
   
    // Configure::write("debug",1);
    if (!empty($options['userId'])) {
        if (!isset($result['error'])) {
            // Update last activity
            LeadManagement::where('cust_id', $options['userId'])->update([
                'last_activity_source' => 'whatsapp',
                'last_activity' => now()->format('Y-m-d H:i:s')
            ]);
        }
    }
 
    if (!empty($result['notification']['_id'])) {
        $messageToLog = $template === 'custom'
            ? $options['message']
            : "Template: " . $template;
    
        $saveData = [
            'user_id' => $options['userId'] ?? 0,
            'message' => $messageToLog,
            'phone' => $sendTo,
            'conversation_id' => $result['notification']['_id'],
            'website' => $siteName,
            'status'     => 0,
            'tracking_id' => $wp_tracking_code ?? null,
           
        ];
    
        if (!empty($options['campaign_id'])) {
            $saveData['campaigns_id'] = $options['campaign_id'];
        }
    
        WhatsappTracker::create($saveData);
    }
    curl_close($ch);
    // var_dump($result);
    return true;
}

 function getWhatsappTemplate($template, $messageData)
{

    // $messageData = ['name'=>'Deepak','email','siteName'=>'GAH','siteFullName'=>'Global Assignment help','siteEmail'=>'help@globalassignmenthelp.com','password'=>'user123','order_code'=>'B45678','order_id'=>'213123','amount'=>'us$ 45','message'=>'','topic'=>'','ddate'=>''];
    $downloadApp = [
        'GAH' => 'bit.ly/gah-App',
        'IAH' => 'bit.ly/iah-App',
        'IAH_AU' => 'bit.ly/iahau-App',
        'AP' => 'bit.ly/ap-App',
        'GAH_AU' => 'bit.ly/gahau-App',
        'AD' => 'bit.ly/ad-App'
    ];

    $loginKey = base64_encode(base64_encode($messageData['siteName'] . "?$&@" . $messageData['userId']));
  //  $amount = 300;
    switch ($template) {
        case 'register':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*$300*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['email'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['password'] . '*',
                ]
              
            ];
            break;
        case 'clarification':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_code'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['message'] . '*',
                ]
            ];
            break;
        case 'quotation':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['siteFullName'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_id'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['topic'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['words'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['ddate'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['amount'] . '*',
                ],
            ];
            break;
        case 'payment_confirmation':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['amount'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_code'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['payee_name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => $downloadApp[$messageData['siteName']],
                ]
            ];
            break;
        case 'payment_reminder':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_code'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['amount'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_code'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['topic'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => $downloadApp[$messageData['siteName']],
                ]
            ];
            break;
        case 'payment_decline':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['amount'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['order_id'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['message'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => $downloadApp[$messageData['siteName']],
                ]
            ];
            break;
        case 'ppc_lead':
            $bodyData = [
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['name'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['email'] . '*',
                ],
                [
                    'type' => 'text',
                    'text' => '*' . $messageData['password'] . '*',
                ]
            ];
            break;
            case 'wallet_update':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*' . $messageData['amount'] . '*',
                    ],
                    // [
                    //     'type' => 'text',
                    //     'text' => '*' . $messageData['message'] . '*',
                    // ]
                ];
                break;
                case 'registration_tool':
                    $bodyData = [
                        [
                            'type' => 'text',
                            'text' => '*' . $messageData['name'] . '*',
                        ],
                    ];
                    break;
                case 'registration_blog':
                    $bodyData = [
                        [
                            'type' => 'text',
                            'text' => '*' . $messageData['name'] . '*',
                        ],
                    ];
                        break;
                case 'registration_sample':
                    $bodyData = [
                        [
                            'type' => 'text',
                            'text' => '*' . $messageData['name'] . '*',
                        ],
                        [
                                'type' => 'text',
                                'text' => '*' . $messageData['sampletitle'] . '*',
                        ]
                    ];
                        break;
                case 'rcb':
                    $bodyData = [];
                    break;
                case 'plagiarism_register':
                    $bodyData = [ [
                        'type' => 'text',
                        'text' => '*' . $messageData['name'] . '*',
                    ]];
                    break;   
                case 'essay_register':
                    $bodyData = [ [
                        'type' => 'text',
                        'text' => '*' . $messageData['name'] . '*',
                    ]];
                    break;
                case 'download_essay':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*' . $messageData['name'] . '*',
                    ]
                ]; 
                break;
                case 'ad_blog_page':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*' . $messageData['name'] . '*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*' . $messageData['title'] . '*',
                    ]
                ]; 
                break;
       
       

       
        case 'web_whatapp':
            $bodyData = [];
            break;
        default:
            return false;
            break;
    }
    if(in_array($template,['clarification','delivery','wallet_update','registration_blog','registration_sample','registration_tool','ad_blog_page'])){
        $loginKey = 'whatsaap.php?id='.$loginKey;
    }

    if(in_array($template,['plagiarism_register'])){
        $loginKey = 'whatsaap.php?id='.$loginKey.'&t=plag';
    }
    if(in_array($template,['essay_register'])){
        $loginKey = 'whatsaap.php?id='.$loginKey.'&t=essay';
    }
   

   if($template == 'download_essay'){
        $btnData = [
            [
                'type' => 'text',
                'text' => $messageData['file'],
            ]
        ];
    }else{
        $btnData = [
                    [
                        'type' => 'text',
                        'text' => $loginKey
                    ]
                ];
    }
  

    if ($template == 'rcb' || $template == 'payment_confirmation') {
        // echo $template; die;
        return ['bodyData' => $bodyData];
    } else {
      
        return ['bodyData' => $bodyData, 'btnData' => $btnData];
    }
}
?>