<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once '../db.php';

$data = json_decode(file_get_contents("php://input"));

if (!empty($data->id) && !empty($data->status)) {
    $id = intval($data->id);
    $status = $conn->real_escape_string($data->status);

    // Validate status value against enum
    $valid_statuses = ['new', 'read', 'replied', 'archived'];
    if (!in_array($status, $valid_statuses)) {
        http_response_code(400);
        echo json_encode(["message" => "Invalid status value."]);
        exit;
    }

    $stmt = $conn->prepare("UPDATE contact_messages SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $id);

    if ($stmt->execute()) {
        http_response_code(200);
        echo json_encode(["message" => "Status updated successfully."]);
    } else {
        http_response_code(503);
        echo json_encode(["message" => "Unable to update status."]);
    }
    $stmt->close();
} else {
    http_response_code(400);
    echo json_encode(["message" => "Incomplete data. ID and Status are required."]);
}

$conn->close();
?>
