<?php

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

if (!($currentHour == 8 && $currentMinute == 0)) {
    echo "⏳ Script runs only at 08:00 AM IST. Current time: " . date('H:i') . "\n";
    exit;
}

require 'vendor/autoload.php';





use Aws\Exception\AwsException;
use Aws\S3\S3Client;
use Aws\Credentials\Credentials;



function imagettftextbold($im, $size, $angle, $x, $y, $color, $font, $text, $boldness = 2)
{
    for ($c1 = 0; $c1 < $boldness; $c1++) {
        for ($c2 = 0; $c2 < $boldness; $c2++) {
            imagettftext($im, $size, $angle, $x + $c1, $y + $c2, $color, $font, $text);
        }
    }
}

$conn = mysqli_connect("localhost", "ihapp_ih_respi1_brithday_cronjob", "9ut*p7GQauKL", "ihapp_respi1_brithday_cronjob");

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



$query = "
    SELECT * 
    FROM `request`
    WHERE cron_status = 0
    AND DAY(STR_TO_DATE(`date`, '%d-%m-%Y')) = DAY(CURDATE())
    AND MONTH(STR_TO_DATE(`date`, '%d-%m-%Y')) = MONTH(CURDATE())
";

// mergeVideo = 5 AND
$results = $conn->query($query);

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

while ($row = $results->fetch_assoc()) {
    $id     = $row['id'];
    $name   = $row['name'];
    $email  = $row['email'];
    $mobile = $row['mobile'];
    $hq     = $row['hq'];
    $static     = 'birthday';

    if ($row['prefix'] == 'Mr.') {
        $text1 = 'his';
        $text2 = 'He';
    } else {
        $text1 = 'her';
        $text2 = 'She';
    }

    // === Inputs ===
    $posterPath = __DIR__ . '/birthday_dynamic_poster2026.png';
    $randomName = rand(10000, 90000);
    $savePath   = __DIR__ . '/output/' . $randomName . '.png';
    $fontFile   = __DIR__ . '/Cabin-Bold.ttf';

    // === Load image ===
    $im = imagecreatefrompng($posterPath);
    imagealphablending($im, true);
    imagesavealpha($im, true);

    $white = imagecolorallocate($im, 255, 255, 255);

    // Measure helper
    $measure = function ($size, $text) use ($fontFile) {
        $bbox = imagettfbbox($size, 0, $fontFile, $text);
        $width  = $bbox[2] - $bbox[0];
        $height = $bbox[1] - $bbox[7];
        $ascent = abs($bbox[7]);
        return [$width, $height, $ascent];
    };

    $boxX = 199;
    $boxY = 818;
    $boxW = 1160;
    $boxH = 119;
    $maxFont = 54;
    $minFont = 16;

    $fitSize = $maxFont;
    for ($s = $maxFont; $s >= $minFont; $s--) {
        [$tw, $th, $asc] = $measure($s, $name);
        if ($tw <= $boxW && $th <= $boxH) {
            $fitSize = $s;
            break;
        }
    }

    [$tw, $th, $asc] = $measure($fitSize, $name);
    $x = $boxX + (int)(($boxW - $tw) / 2);
    $y = $boxY + (int)(($boxH - $th) / 2) + $asc;

    // ✅ Call function defined at top
    imagettftextbold($im, $fitSize, 0, $x, $y, $white, $fontFile, $name, 2);

    // Save image
    imagepng($im, $savePath);
    imagedestroy($im);
    if (file_exists($savePath) && filesize($savePath) > 0) {

        $credentials = new Credentials('DO801LGZNFRKJF8BAG6X', 'SNPuRgqyWoMmb2b9yxcyJLrFVFTkE55XGUH1JgYykgg');

        $spaces = new S3Client([
            'version'     => 'latest',
            'region'      => 'blr1', // your region
            'endpoint'    => 'https://blr1.digitaloceanspaces.com',
            'credentials' => $credentials,
        ]);

        $bucketName = 'imagicahealth'; // your bucket
        $filePath   = __DIR__ . '/output/' . $randomName . '.png'; // local generated file
        $fileName   = 'ihapp_respi1_brithday_cronjob/' . basename($filePath); // object key in bucket

        try {

            $result = $spaces->putObject([
                'Bucket'      => $bucketName,
                'Key'         => $fileName,
                'SourceFile'  => $filePath,       // upload file directly
                'ACL'         => 'public-read',   // optional, makes it public
                'ContentType' => 'image/png'
            ]);

            $imageUrl = "https://{$bucketName}.blr1.digitaloceanspaces.com/{$fileName}";

            // Update DB with uploaded file URL
            $update = "UPDATE `request` 
               SET image_url = '" . mysqli_real_escape_string($conn, $imageUrl) . "'
               WHERE id = " . intval($id);

            if ($conn->query($update)) {
                echo "✅ Image uploaded & DB updated: $imageUrl\n";
            } else {
                $sql = "INSERT INTO `cron_log`(`error`) VALUES ($id.'image not create')";
                $sqls = $conn->query($sql);
                echo "❌ DB Update Error: " . $conn->error;
            }

            $fileContent = file_get_contents($filePath);
            $base64File  = base64_encode($fileContent);

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

            $data = json_encode([
                "template_key" => "2518b.40f38d0712830fa4.k1.392e3840-826a-11f0-9b1c-525400c92439.198e5fe81c4",
                "from" => [
                    "address" => "vanita@vinciohealth.in",
                    "name" => "Imagicahealth"
                ],
                "to" => [
                    ["email_address" => ["address" => "rupesh.joshi87@gmail.com"]],
                    ["email_address" => ["address" => "rupesh.joshi@cipla.com"]],
                    ["email_address" => ["address" => "medicalservices@imagicahealth.com"]],
                ],
                "subject" => "DECODE:COUGH WEBINAR III",
                "merge_info" => [
                    "name" => $name,
                    "email" => $email,
                    "hq" => $hq,
                    "mobile" => $mobile,
                    "text1" => $text1,
                    "text2" => $text2,
                ],
                "attachments" => [
                    [
                        "name" => basename($filePath),
                        "mime_type" => "image/png",
                        "content" => $base64File
                    ]
                ]
            ]);



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

            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);

            if ($response === false) {
                echo "cURL Error: " . curl_error($ch);
            }
            echo $response;

            curl_close($ch);

            $update = "UPDATE `request` 
               SET cron_status = 1 
               WHERE id = " . intval($id);

            if ($conn->query($update)) {
                echo "✅ Image uploaded & DB updated: $imageUrl\n";
                error_log("Image uploaded & DB updated: $imageUrl\n");
                $mobileNumbers = ['918140920008', '919822579880', '919512121898'];

                $url = '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" => $imageUrl
                                            ]
                                        ]
                                    ]
                                ],
                                [
                                    'type' => 'body',
                                    'parameters' => [
                                        ['type' => 'text', 'text' => $static],
                                        ['type' => 'text', 'text' => $name],
                                        ['type' => 'text', 'text' => $hq],
                                        ['type' => 'text', 'text' => $email],
                                        ['type' => 'text', 'text' => $mobile]
                                    ]
                                ]
                            ]
                        ]
                    ];

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

                    $response = curl_exec($ch);
                    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                }

                if (curl_errno($ch)) {
                    echo 'Curl error: ' . curl_error($ch);
                    $sts = 20;
                } else {
                    if ($httpCode !== 200) {
                        echo "Failed to send message. HTTP Status: $httpCode\n";
                        echo "Response: $response\n";
                        $sts = 20;
                    } else {
                        $responseBody = json_decode($response, true);
                        if (
                            isset($responseBody['messages'][0]['message_status']) &&
                            $responseBody['messages'][0]['message_status'] === 'accepted'
                        ) {
                            echo json_encode(['status' => true]);
                            curl_close($ch);
                            $sts = 15;
                            // exit;
                        } else {
                            $sts = 20;
                            echo "Message not accepted.\n";
                            print_r($responseBody);
                        }
                    }
                }
                $updateQuery2 = "UPDATE request SET cron_status = $sts WHERE id = '$id'";
                mysqli_query($conn, $updateQuery2);
            } else {
                $update = "UPDATE `request` 
               SET cron_status = 2
               WHERE id = " . intval($id);
                $conn->query($update);
                echo "❌ DB Update Error: " . $conn->error;
                error_log("❌ DB Update Error: " . $conn->error);
                $sql = "INSERT INTO `cron_log`(`error`) VALUES ($id.'mail not send')";
                $sqls = $conn->query($sql);
            }
        } catch (AwsException $e) {
            $update = "UPDATE `request` 
               SET cron_status = 2
               WHERE id = " . intval($id);
            $conn->query($update);
            echo "Upload failed: " . $e->getMessage();
            error_log("Upload failed: " . $e->getMessage());
        }
    }
}
