<?php

session_start();

require '../../config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_email'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$connect = connect($database);
require '../functions.php';

$check_access = check_access($connect);

if ($check_access['user_role'] != 1 && $check_access['user_role'] != 2) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$contact_id = isset($_POST['contact_id']) ? intval($_POST['contact_id']) : 0;
$status = isset($_POST['status']) ? $_POST['status'] : '';

if ($contact_id <= 0 || !in_array($status, ['new', 'read', 'replied'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

$stmt = $connect->prepare("UPDATE contact_messages SET contact_status = ? WHERE contact_id = ?");
$stmt->execute([$status, $contact_id]);

if ($stmt->rowCount() > 0) {
    echo json_encode(['success' => true, 'message' => 'Status updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Update failed']);
}

?>
