<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

date_default_timezone_set('Asia/Kolkata');
$currentHour = date('H');
$currentMinute = date('i');

// === CRON TIME CHECK ===
if (!($currentHour == 11 && $currentMinute == 0)) {
// if (!($currentHour == 9 && $currentMinute == 33)) {
    echo "Script runs only at 11:00 AM IST. Current time: " . date('H:i') . "\n";
    exit;
}

$conn = mysqli_connect("localhost", "fastshare_imagica", "Imagica@6092", "fastshare_respi1");

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();
}

$date = date('d-m');

$query = "SELECT salesvideorequest.*, tbl_users.emailid
FROM salesvideorequest
LEFT JOIN tbl_users 
    ON salesvideorequest.uniqueId = tbl_users.unique_id
WHERE (DATE_FORMAT(salesvideorequest.anniversarydate, '%d-%m') = '{$date}')
ORDER BY salesvideorequest.id DESC";

$results = $conn->query($query);

if ($results->num_rows == 0) {
    echo "No Record Found !!!!";
    exit;
}

// STATIC POSTER PATH (NO EDITING)
$staticPoster = __DIR__ . '/anniversary_static_poster2026.png';

if (!file_exists($staticPoster)) {
    die("Static poster NOT FOUND!");
}

// --- MAIN LOOP ---
while ($row = $results->fetch_assoc()) {

    $id = $row['id'];
    echo $id;
    // exit;
    $name = $row['name'];
    $email = (!empty($row['emailid']) && $row['emailid'] != 0) ? $row['emailid'] : '-';
    $mobile = $row['mobile'];
    $hq = $row['hq'];
    $static = 'anniversary';

    // Gender prefix logic
    if ($row['gender'] == 'Male') {
        $text1 = 'his';
        $text2 = 'He';
    } else {
        $text1 = 'her';
        $text2 = 'She';
    }

    // Convert static image to base64
    $fileContent = file_get_contents($staticPoster);
    $base64File = base64_encode($fileContent);


    // -------------------------- EMAIL SENDING --------------------------
    $ch = curl_init();
    $url = "https://api.zeptomail.in/v1.1/email/template";

    $data = json_encode([
        "template_key" => "2518b.40f38d0712830fa4.k1.429010a1-c53d-11f0-95d1-cabf48e1bf81.19a9bef2ea5",
        "from" => [
            "address" => "vanita@vinciohealth.in",
            "name" => "Imagicahealth"
        ],
        "to" => [
            ["email_address" => ["address" => "rupesh.joshi87@gmail.com"]],
            ["email_address" => ["address" => "medicalservices@imagicahealth.com"]],
            ["email_address" => ["address" => "rupesh.joshi@cipla.com"]],
            ["email_address" => ["address" => "harshad.patil1@Cipla.com"]],
            // ["email_address" => ["address" => "dhruvilmiyani300@gmail.com"]],
        ],
        "subject" => "DECODE:COUGH WEBINAR III",
        "merge_info" => [
            "name" => $name,
            "email" => $email,
            "hq" => $hq,
            "mobile" => $mobile,
            "text1" => $text1,
            "text2" => $text2,
        ],
        "attachments" => [
            [
                "name" => "Anniversary.png",
                "mime_type" => "image/png",
                "content" => $base64File
            ]
        ]
    ]);

    $headers = [
        'Accept: application/json',
        'Content-Type: application/json',
        'Authorization: Zoho-enczapikey PHtE6r0MQ+Dj3WR6oxFT56K4RZXyPdksrLlkLwFBs4lFD6NVSk0A/owqwTOwrB0sVqRDFKWSmtpgtbucsr3XcWjrNm9MVGqyqK3sx/VYSPOZsbq6x00asVkTfkLaV4LoddFi1CzTv9uX'
    ];

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);
    echo '<pre>';
    print_r($response);


    // -------------------------- SEND WHATSAPP --------------------------
    $mobileNumbers = ['919822579880', '919512121898','919538417380','919510585838','919924088835'];

    // $mobileNumbers = ['919510585838','919924088835','919512121898'];
    // $mobileNumbers = ['919512121898', '919924433851'];

    $waUrl = 'https://graph.facebook.com/v19.0/115951338127454/messages';
    $accessToken = 'EAANZAiqV709EBAH3sv0oczMfNPQomdX6MVI5G9DvWrtXSvV3sCNAbzMcfhn8vPKX6DA2N7YJGLtECi0KzhSby4ooxo0FubO0dZAHuZCghx2IWTikMpU8xKj3TpFZAWQo90SWToXQ0Pc0VvR2KKUmzaD41xXba1B73mLsgZBZBx1HCUZAeS2ZAXxW';

    foreach ($mobileNumbers as $mr_mobile) {
        $payload = [
            'messaging_product' => 'whatsapp',
            'recipient_type' => 'individual',
            'to' => $mr_mobile,
            'type' => 'template',
            'template' => [
                'name' => 'b_reminder_invoice330',
                'language' => ['code' => 'en'],
                'components' => [
                    [
                        "type" => "header",
                        "parameters" => [
                            [
                                "type" => "image",
                                "image" => [
                                    "link" => "https://ih.imagicahealth.in/respi1/salesteam_message/static_poster.png"
                                ]
                            ]
                        ]
                    ],
                    [
                        'type' => 'body',
                        'parameters' => [
                            ['type' => 'text', 'text' => $static],
                            ['type' => 'text', 'text' => $name],
                            ['type' => 'text', 'text' => $hq],
                            ['type' => 'text', 'text' => $email],
                            ['type' => 'text', 'text' => $mobile]
                        ]
                    ]
                ]
            ]
        ];

        $ch2 = curl_init($waUrl);
        curl_setopt($ch2, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch2, CURLOPT_POST, true);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($payload));

        $response2 = curl_exec($ch2);
        echo '<pre>';
        print_r($response2);
        curl_close($ch2);
    }


    // UPDATE CRON STATUS
    // $conn->query("UPDATE salesvideorequest SET cron_status = 1 WHERE id = $id");

    echo "✔ Completed for ID: $id\n";
}
