<?php
// File: /admin/ticket_handler.php
session_start();
require_once __DIR__ . '/../db.php';

// Security: Only admins can perform these actions
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied. You do not have permission to perform this action.");
}
$admin_id = $_SESSION['user_id'];

// --- HANDLE ADDING A REPLY ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['add_reply']) || isset($_POST['add_reply_and_close']))) {
    
    $ticket_id = filter_var($_POST['ticket_id'], FILTER_SANITIZE_NUMBER_INT);
    $message = htmlspecialchars(trim($_POST['message']));

    if (empty($message) || empty($ticket_id)) {
        header('Location: ticket_view.php?id=' . $ticket_id . '&error=empty_reply');
        exit();
    }

    // Insert the admin's reply into the replies table
    $stmt_insert = $conn->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message) VALUES (?, ?, ?)");
    $stmt_insert->bind_param("iis", $ticket_id, $admin_id, $message);
    $stmt_insert->execute();

    // Determine the new status for the parent ticket
    $new_status = 'answered'; // Default status when replying
    if (isset($_POST['add_reply_and_close'])) {
        $new_status = 'closed';
    }

    // Update the parent ticket's status and last updated time
    $stmt_update = $conn->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt_update->bind_param("si", $new_status, $ticket_id);
    $stmt_update->execute();

    // Optionally, you could add logic here to send an email notification to the user
    // telling them their ticket has been updated.

    header('Location: ticket_view.php?id=' . $ticket_id . '&status=replied');
    exit();
}


// --- HANDLE CLOSING A TICKET WITHOUT A REPLY ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_ticket'])) {
    $ticket_id = filter_var($_POST['ticket_id'], FILTER_SANITIZE_NUMBER_INT);

    $stmt_update = $conn->prepare("UPDATE support_tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
    $stmt_update->bind_param("i", $ticket_id);
    $stmt_update->execute();

    header('Location: ticket_view.php?id=' . $ticket_id . '&status=closed');
    exit();
}


// Default redirect if no valid action is matched
header('Location: tickets.php');
exit();
?>

