<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if we have the necessary parameters
$ticket_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$csrf_token = $_GET['csrf_token'] ?? '';

// Validate CSRF token
if (!$csrf_token || !hash_equals($_SESSION['csrf_token'], $csrf_token)) {
    $_SESSION['error_message'] = "Invalid security token. Action denied for your protection.";
    header("Location: tickets.php");
    exit();
}

// Validate ticket ID
if (!$ticket_id) {
    $_SESSION['error_message'] = "Invalid ticket ID.";
    header("Location: tickets.php");
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Begin transaction
    $db->beginTransaction();
    
    // First, check if the ticket exists
    $stmt = $db->prepare("SELECT id, user_id, subject FROM tickets WHERE id = ?");
    $stmt->execute([$ticket_id]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        throw new Exception("Ticket not found.");
    }
    
    // Store user_id for notification
    $user_id = $ticket['user_id'];
    $ticket_subject = $ticket['subject'];
    
    // Delete all ticket messages
    $stmt = $db->prepare("DELETE FROM ticket_messages WHERE ticket_id = ?");
    $stmt->execute([$ticket_id]);
    $messages_deleted = $stmt->rowCount();
    
    // Delete the ticket
    $stmt = $db->prepare("DELETE FROM tickets WHERE id = ?");
    $stmt->execute([$ticket_id]);
    $ticket_deleted = $stmt->rowCount();
    
    // Create a notification for the user about the deleted ticket
    $notification_title = "Ticket Deleted";
    $notification_message = "Your ticket #$ticket_id: '$ticket_subject' has been deleted by an administrator.";
    
    $stmt = $db->prepare("
        INSERT INTO notifications (user_id, type, title, message, created_at)
        VALUES (?, 'ticket_deleted', ?, ?, NOW())
    ");
    $stmt->execute([$user_id, $notification_title, $notification_message]);
    
    // Log the deletion
    error_log("Admin deleted ticket #$ticket_id: '$ticket_subject'. Messages deleted: $messages_deleted");
    
    // Commit the transaction
    $db->commit();
    
    // Set success message
    $_SESSION['success_message'] = "Ticket #$ticket_id has been permanently deleted.";
    
    // Redirect back to the tickets page
    header("Location: tickets.php");
    exit();
    
} catch (Exception $e) {
    // Rollback the transaction on error
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    
    $_SESSION['error_message'] = "Failed to delete ticket: " . $e->getMessage();
    header("Location: tickets.php");
    exit();
}
?>
