<?php
// Include header (which includes all dependencies)
include 'includes/header.php';

// Delete restricted to administrators
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_NO_PERMISSION_DELETE_TICKETS'] ?? 'You do not have permission to delete tickets', 'danger');
    redirectTo('tickets');
    exit;
}

// Check if request is POST and contains valid CSRF token
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_REQUEST_METHOD'] ?? 'Invalid request method. Please use the provided delete button.', 'danger');
    redirectTo('tickets');
    exit;
}

if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_SECURITY_TOKEN'] ?? 'Invalid security token. Please try again.', 'danger');
    redirectTo('tickets');
    exit;
}

// Get ticket ID from various possible sources
// 1. POST 'id' - used by frontend tickets.php modal
// 2. POST 'delete_ticket' - used by admin/tickets.php modal (for compatibility)
// 3. GET 'id' - provided by router for dynamic routes like /ticket_delete/123
$ticket_id = (int) ($_POST['id'] ?? $_POST['delete_ticket'] ?? $_GET['id'] ?? 0);

// If no ticket ID provided, redirect to tickets page
if ($ticket_id <= 0) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_TICKET_ID'] ?? 'Invalid ticket ID', 'danger');
    redirectTo('tickets');
    exit;
}

// Delete the ticket
try {
    deleteTicketAttachmentFilesFromDisk($pdo, $ticket_id);

    // First delete all replies (this should be handled by the ON DELETE CASCADE, but we make sure)
    $stmt = $pdo->prepare("DELETE FROM ticket_replies WHERE ticket_id = ?");
    $stmt->execute([$ticket_id]);

    // Then delete the ticket
    $stmt = $pdo->prepare("DELETE FROM tickets WHERE id = ?");
    $stmt->execute([$ticket_id]);

    if ($stmt->rowCount() > 0) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_TICKET_DELETED'] ?? 'Ticket deleted successfully');
    } else {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_TICKET_NOT_FOUND'] ?? 'Ticket not found', 'warning');
    }
} catch (PDOException $e) {
    $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_ERROR_DELETING_TICKET'] ?? 'Error deleting ticket: %s', $e->getMessage()), 'danger');
    error_log("Error deleting ticket: " . $e->getMessage());
}

// Redirect to tickets page
redirectTo('tickets');
exit;
?>