<?php
// 1. INCLUDE THE DASHBOARD HEADER
// Handles security, DB connection, user data, and the top navbar.
include 'header.php';

// --- Page-Specific Logic Starts Here ---
// The $user_id and $user_header_data variables are available from header.php

// 2. HANDLE NEW TICKET FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_ticket') {
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);
    $priority = $_POST['priority'] === 'High' ? 'High' : 'Normal';
    
    if (!empty($subject) && !empty($message)) {
        // Generate a unique ticket reference
        $ticket_ref = "TKT-" . time() . strtoupper(bin2hex(random_bytes(2)));

        $stmt = $conn->prepare("INSERT INTO support_tickets (user_id, ticket_ref, subject, message, priority) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issss", $user_id, $ticket_ref, $subject, $message, $priority);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Your support ticket (#{$ticket_ref}) has been submitted successfully. Our team will get back to you shortly.";
        } else {
            $_SESSION['error_message'] = "There was an error submitting your ticket. Please try again.";
        }
        $stmt->close();
    } else {
        $_SESSION['error_message'] = "Please provide both a subject and a message for your ticket.";
    }
    header("Location: support.php");
    exit();
}

// 3. FETCH USER'S EXISTING SUPPORT TICKETS
$stmt_tickets = $conn->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC");
$stmt_tickets->bind_param("i", $user_id);
$stmt_tickets->execute();
$tickets = $stmt_tickets->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_tickets->close();
?>

<div class="container my-5">
    <div class="dashboard-content">
        <h1 class="h2 mb-4">Help & Support</h1>

        <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-lg-7">
                <div class="card shadow-sm">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="bi bi-pencil-square me-2"></i>Submit a New Ticket</h5>
                    </div>
                    <div class="card-body p-4">
                        <form action="support.php" method="POST">
                            <input type="hidden" name="action" value="submit_ticket">
                            <div class="mb-3">
                                <label for="subject" class="form-label">Subject</label>
                                <input type="text" class="form-control" id="subject" name="subject" required>
                            </div>
                            <div class="mb-3">
                                <label for="message" class="form-label">Message</label>
                                <textarea class="form-control" id="message" name="message" rows="8" required placeholder="Please describe your issue in detail..."></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="priority" class="form-label">Priority</label>
                                <select class="form-select" id="priority" name="priority">
                                    <option value="Normal" selected>Normal</option>
                                    <option value="High">High</option>
                                </select>
                            </div>
                            <div class="d-flex justify-content-end mt-4">
                                <button type="submit" class="btn btn-primary">Submit Ticket</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-5">
                 <div class="card shadow-sm">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Your Ticket History</h5>
                    </div>
                    <?php if (!empty($tickets)): ?>
                    <div class="list-group list-group-flush">
                        <?php foreach ($tickets as $ticket): ?>
                        <a href="#" class="list-group-item list-group-item-action">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1"><?php echo htmlspecialchars($ticket['subject']); ?></h6>
                                <?php $status_badge = ['Open' => 'success', 'Answered' => 'primary', 'Closed' => 'secondary']; ?>
                                <span class="badge bg-<?php echo $status_badge[$ticket['status']] ?? 'light'; ?>"><?php echo htmlspecialchars($ticket['status']); ?></span>
                            </div>
                            <p class="mb-1 small text-muted">Ticket #: <?php echo htmlspecialchars($ticket['ticket_ref']); ?></p>
                            <small>Submitted: <?php echo date('M d, Y', strtotime($ticket['created_at'])); ?></small>
                        </a>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="card-body text-center p-4">
                        <p class="text-muted mb-0">You have not submitted any support tickets yet.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>
