<?php
/**
 * support_update.php - Quick status update
 */

require_once 'config.php';
checkAdminAuth();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ticket_id = (int)$_POST['ticket_id'];
    $status = $_POST['status'];
    
    // Validate status
    $allowed_statuses = ['pending', 'in_progress', 'resolved'];
    if (!in_array($status, $allowed_statuses)) {
        die('Invalid status');
    }
    
    // Use prepared statement to prevent SQL injection
    $stmt = $conn->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->bind_param("si", $status, $ticket_id);
    $stmt->execute();
    $stmt->close();
    
    // Add system message when ticket is resolved
    if ($status === 'resolved') {
        $message = "تم إغلاق التذكرة. شكراً لتواصلك مع ماكس بروست.";
        $msg_stmt = $conn->prepare("
            INSERT INTO support_messages (ticket_id, sender_type, message, created_at) 
            VALUES (?, 'system', ?, NOW())
        ");
        $msg_stmt->bind_param("is", $ticket_id, $message);
        $msg_stmt->execute();
    }
}

// Redirect back to the ticket
if (isset($_POST['ticket_id'])) {
    header('Location: support.php?ticket=' . $ticket_id);
} else {
    header('Location: support.php');
}
exit;