<?php
// This file should be set as a Cron Job to run every hour
include __DIR__ . '/../config/config.php';

/**
 * Function to trigger Mailchimp Transactional Email
 */
function sendMailchimpAlert($to_emails, $subject, $message_html) {
    $url = "https://" . MAILCHIMP_SERVER . ".api.mailchimp.com/3.0/messages/send";
    
    $recipients = [];
    foreach($to_emails as $email) {
        $recipients[] = ["email" => $email, "type" => "to"];
    }

    $data = [
        "key" => MAILCHIMP_API_KEY,
        "message" => [
            "html" => $message_html,
            "subject" => $subject,
            "from_email" => ADMIN_EMAIL,
            "from_name" => "Swarnavahini Ratings",
            "to" => $recipients
        ]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\nAuthorization: Basic " . base64_encode("user:" . MAILCHIMP_API_KEY) . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ]
    ];

    $context  = stream_context_create($options);
    return @file_get_contents($url, false, $context);
}

// 1. Get all member emails
$members = $pdo->query("SELECT email FROM users WHERE role = 'member'")->fetchAll(PDO::FETCH_COLUMN);

if (empty($members)) exit("No members found.");

// 2. CHECK FOR 12-HOUR MARK (First Warning)
// Finds dramas created between 12 and 13 hours ago
$stmt12 = $pdo->query("SELECT title FROM dramas WHERE created_at <= DATE_SUB(NOW(), INTERVAL 12 HOUR) AND created_at > DATE_SUB(NOW(), INTERVAL 13 HOUR)");
$dramas12 = $stmt12->fetchAll();

foreach ($dramas12 as $d) {
    $msg = "<h2>Halfway there!</h2><p>The production <b>{$d['title']}</b> was added 12 hours ago. You have 12 hours left to submit your evaluation.</p>";
    sendMailchimpAlert($members, "12 Hour Warning: " . $d['title'], $msg);
}

// 3. CHECK FOR 23-HOUR MARK (Final Warning)
// Finds dramas created between 23 and 24 hours ago
$stmt23 = $pdo->query("SELECT title FROM dramas WHERE created_at <= DATE_SUB(NOW(), INTERVAL 23 HOUR) AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)");
$dramas23 = $stmt23->fetchAll();

foreach ($dramas23 as $d) {
    $msg = "<h2>Final Hour!</h2><p>URGENT: Only 1 hour remains to rate <b>{$d['title']}</b>. After this, the window will close forever.</p>";
    sendMailchimpAlert($members, "URGENT: 1 Hour Left for " . $d['title'], $msg);
}

echo "Cron processed successfully.";