<?php
require_once __DIR__ . '/session_check.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/activity_logger.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../scheduled_messages.php');
    exit();
}

$scheduleId = $_POST['schedule_id'] ?? null;
$action = $_POST['action'] ?? null;
$userId = $_SESSION['user_id'];

if (!$scheduleId || !$action) {
    header('Location: ../scheduled_messages.php?error=missing_data');
    exit();
}

$pdo->beginTransaction();
try {
    $newStatus = '';
    $successMessage = '';

    switch ($action) {
        case 'disable':
            $newStatus = 'disabled';
            $successMessage = 'disabled';
            log_activity($userId, 'Message Disabled', 'Schedule ID: ' . $scheduleId);
            break;
        case 'enable':
            $newStatus = 'pending';
            $successMessage = 'enabled';
            log_activity($userId, 'Message Enabled', 'Schedule ID: ' . $scheduleId);
            break;
        case 'cancel':
            $newStatus = 'cancelled';
            $successMessage = 'cancelled';
            log_activity($userId, 'Message Sending Cancelled', 'Schedule ID: ' . $scheduleId);
            break;
        case 'retry':
            $newStatus = 'pending';
            $successMessage = 'retried';
            log_activity($userId, 'Message Retried', 'Schedule ID: ' . $scheduleId);
            break;
        case 'delete':
            $stmt = $pdo->prepare("DELETE FROM schedules WHERE id = ?");
            $stmt->execute([$scheduleId]);
            $successMessage = 'deleted';
            log_activity($userId, 'Message Deleted', 'Schedule ID: ' . $scheduleId);
            break;
        default:
            throw new Exception('Invalid action specified.');
    }

    if ($newStatus) {
        $stmt = $pdo->prepare("UPDATE schedules SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $scheduleId]);
    }

    $pdo->commit();
    header("Location: ../scheduled_messages.php?success={$successMessage}");
    exit();

} catch (Exception $e) {
    $pdo->rollBack();
    error_log("ScheduleActions Error: " . $e->getMessage());
    header('Location: ../scheduled_messages.php?error=dberror');
    exit();
}
