<?php
session_start();
include('includes/head.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';

if ($submitted_pin !== $admin_pin) {
    header('Location: support_tickets.php?error=Invalid PIN. Ticket not created.');
    exit();
}

// Get form data
$user_id = intval($_POST['user_id']);
$subject = mysqli_real_escape_string($conn, $_POST['subject']);
$category = mysqli_real_escape_string($conn, $_POST['category']);
$priority = mysqli_real_escape_string($conn, $_POST['priority']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
$assign_to = intval($_POST['assign_to']);

// Generate ticket number
$ticket_number = 'TKT-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 6));

// Insert ticket
$sql = "INSERT INTO support_tickets (user_id, ticket_number, subject, category, priority, description, assigned_to, created_at, updated_at) 
        VALUES ($user_id, '$ticket_number', '$subject', '$category', '$priority', '$description', $assign_to, NOW(), NOW())";

if (mysqli_query($conn, $sql)) {
    $ticket_id = mysqli_insert_id($conn);
    
    // Add first message from admin
    $reply_sql = "INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply, created_at) 
                  VALUES ($ticket_id, " . $_SESSION['admin_id'] . ", 'Ticket opened by admin.', 1, NOW())";
    mysqli_query($conn, $reply_sql);
    
    // Log activity
    logAdminActivity(
        'Ticket Created',
        "Created ticket #$ticket_number for user ID $user_id",
        'Support',
        $ticket_id,
        'support_tickets'
    );
    
    header('Location: support_tickets.php?success=Ticket created successfully!');
} else {
    header('Location: support_tickets.php?error=Failed to create ticket.');
}
exit();
?>