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

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

// Basic validation
if (empty($_POST['messageContent']) || empty($_POST['recipientId']) || empty($_POST['schedule_id']) || empty($_POST['message_id'])) {
    header('Location: ../edit_message.php?schedule_id=' . $_POST['schedule_id'] . '&error=missing_fields');
    exit();
}

$scheduleId = $_POST['schedule_id'];
$messageId = $_POST['message_id'];
$content = $_POST['messageContent'];
$recipientId = $_POST['recipientId'];
$scheduleDateTime = $_POST['scheduleDateTime'] ?? date('Y-m-d H:i:s');

$pdo->beginTransaction();

try {
    // 1. Update the message content
    $stmt = $pdo->prepare("UPDATE messages SET content = ? WHERE id = ?");
    $stmt->execute([$content, $messageId]);

    // 2. Update the schedule
    // When editing, we reset its status to 'pending' so the worker can pick it up again.
    $stmt = $pdo->prepare(
        "UPDATE schedules SET recipient_id = ?, send_time = ?, status = 'pending' WHERE id = ?"
    );
    $stmt->execute([$recipientId, $scheduleDateTime, $scheduleId]);

    $pdo->commit();

    // Redirect to a success page
    header('Location: ../scheduled_messages.php?success=updated');
    exit();

} catch (Exception $e) {
    $pdo->rollBack();
    error_log("Message update failed: " . $e->getMessage());
    header('Location: ../edit_message.php?schedule_id=' . $scheduleId . '&error=dberror');
    exit();
}
?>