<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = isset($_POST['action']) ? trim($_POST['action']) : '';

// ═══════════════════════════════════════════════════════════════
//  CANCEL A SCHEDULED EMAIL
// ═══════════════════════════════════════════════════════════════
if ($action === 'cancel') {
    $email_id = filter_var($_POST['email_id'] ?? 0, FILTER_VALIDATE_INT);
    if (!$email_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid email ID']);
        exit();
    }

    try {
        $stmt = $pdo->prepare("DELETE FROM scheduled_emails WHERE id = ? AND status = 'pending'");
        $stmt->execute([$email_id]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => '1', 'msg' => 'Scheduled email cancelled successfully.']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Email not found or already sent.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ═══════════════════════════════════════════════════════════════
//  SCHEDULE A NEW EMAIL
// ═══════════════════════════════════════════════════════════════
if ($action === 'schedule') {
    $recipient_type = isset($_POST['recipient_type']) ? trim($_POST['recipient_type']) : '';
    $subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    $scheduled_at = isset($_POST['scheduled_at']) ? trim($_POST['scheduled_at']) : '';

    // Validate
    if (empty($subject)) {
        echo json_encode(['status' => '0', 'msg' => 'Email subject is required']);
        exit();
    }
    if (empty($message)) {
        echo json_encode(['status' => '0', 'msg' => 'Email message is required']);
        exit();
    }
    if (!in_array($recipient_type, ['individual', 'all'])) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid recipient type']);
        exit();
    }
    if (empty($scheduled_at)) {
        echo json_encode(['status' => '0', 'msg' => 'Please select a schedule date and time']);
        exit();
    }

    // Validate date is in the future
    $schedule_time = strtotime($scheduled_at);
    if ($schedule_time === false || $schedule_time < time()) {
        echo json_encode(['status' => '0', 'msg' => 'Schedule time must be in the future']);
        exit();
    }

    // Get user IDs for individual sends
    $user_ids_str = null;
    if ($recipient_type === 'individual') {
        $user_ids = isset($_POST['user_ids']) ? $_POST['user_ids'] : [];
        if (empty($user_ids)) {
            echo json_encode(['status' => '0', 'msg' => 'Please select at least one recipient']);
            exit();
        }
        $user_ids_str = implode(',', array_map('intval', $user_ids));
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO scheduled_emails (subject, message, recipient_type, user_ids, scheduled_at, status, created_by) VALUES (?, ?, ?, ?, ?, 'pending', ?)");
        $stmt->execute([
            $subject,
            $message,
            $recipient_type,
            $user_ids_str,
            date('Y-m-d H:i:s', $schedule_time),
            $_SESSION['user_id']
        ]);

        $formatted_time = date('M d, Y h:i A', $schedule_time);
        echo json_encode(['status' => '1', 'msg' => "Email scheduled successfully for <strong>{$formatted_time}</strong>"]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Invalid action']);
?>
