<?php
include '../db.php';
include 'whatsapp_api.php'; // Helper for WhatsApp API

$today = date('Y-m-d');
$target = date('Y-m-d', strtotime('+30 days'));

// Fetch all expiring domains, hostings, emails within next 30 days
$queries = [
    'domains' => "SELECT d.*, c.name, c.email, c.phone FROM domains d JOIN clients c ON d.client_id=c.id WHERE expiry_date BETWEEN '$today' AND '$target'",
    'hostings' => "SELECT h.*, c.name, c.email, c.phone FROM hostings h JOIN clients c ON h.client_id=c.id WHERE expiry_date BETWEEN '$today' AND '$target'",
    'emails' => "SELECT e.*, c.name, c.email, c.phone FROM emails e JOIN clients c ON e.client_id=c.id WHERE renewal_date BETWEEN '$today' AND '$target'",
];

foreach ($queries as $type => $sql) {
    $stmt = $conn->query($sql);
    $records = $stmt->fetchAll();

    foreach ($records as $rec) {
        // Compose message & subject based on type
        switch($type) {
            case 'domains':
                $subject = "Domain Expiry Reminder: {$rec['domain_name']}";
                $message = "Dear {$rec['name']}, your domain {$rec['domain_name']} will expire on {$rec['expiry_date']}. Please renew soon.";
                break;
            case 'hostings':
                $subject = "Hosting Expiry Reminder: {$rec['plan']}";
                $message = "Dear {$rec['name']}, your hosting plan '{$rec['plan']}' will expire on {$rec['expiry_date']}. Please renew soon.";
                break;
            case 'emails':
                $subject = "Email Renewal Reminder: {$rec['email_address']}";
                $message = "Dear {$rec['name']}, your email {$rec['email_address']} will need renewal by {$rec['renewal_date']}. Please renew soon.";
                break;
        }

        // Send Email
        $email_sent = mail($rec['email'], $subject, $message, "From: admin@yourdomain.com");

        // Send WhatsApp
        $wa_sent = sendWhatsApp($rec['phone'], $message);

        // Log notification
        $stmt_log = $conn->prepare("INSERT INTO notification_logs (client_id, type, subject, message, status) VALUES (?, ?, ?, ?, ?)");
        $stmt_log->execute([
            $rec['client_id'],
            'email',
            $subject,
            $message,
            $email_sent ? 'success' : 'failed'
        ]);
        $stmt_log->execute([
            $rec['client_id'],
            'whatsapp',
            $subject,
            $message,
            $wa_sent ? 'success' : 'failed'
        ]);
    }
}
