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

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_ticket'])) {
    $ticket_id = filter_input(INPUT_POST, 'ticket_id', FILTER_VALIDATE_INT);
    
    if (!$ticket_id) {
        $_SESSION['error_message'] = "Invalid ticket ID.";
        header("Location: tickets.php");
        exit();
    }
    
    // Verify the ticket belongs to the user
    $stmt = $db->prepare("SELECT id, subject FROM tickets WHERE id = ? AND user_id = ?");
    $stmt->execute([$ticket_id, $_SESSION['user_id']]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        $_SESSION['error_message'] = "Invalid ticket or permission denied.";
        header("Location: tickets.php");
        exit();
    }
    
    try {
        $db->beginTransaction();
        
        // Update ticket status
        $stmt = $db->prepare("UPDATE tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$ticket_id]);
        
        // Add a system message
        $stmt = $db->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, is_admin, message) VALUES (?, ?, 1, ?)");
        $stmt->execute([$ticket_id, $_SESSION['user_id'], "Ticket closed by user."]);
        
        // Create notification for admins
        $stmt = $db->prepare("
            INSERT INTO admin_notifications (type, title, message, link) 
            VALUES ('ticket_closed', 'Ticket Closed', ?, ?)
        ");
        $stmt->execute([
            'Ticket #' . $ticket_id . ' (' . $ticket['subject'] . ') has been closed by the user.',
            'admin/ticket_details.php?id=' . $ticket_id
        ]);
        
        $db->commit();
        $_SESSION['success_message'] = "Ticket has been closed successfully.";
    } catch (PDOException $e) {
        $db->rollBack();
        $_SESSION['error_message'] = "An error occurred while closing the ticket.";
        error_log("Close Ticket Error: " . $e->getMessage());
    }
    
    header("Location: ticket_details.php?id=" . $ticket_id);
    exit();
} else {
    header("Location: tickets.php");
    exit();
}
?>
