<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Get tickets for the current user
$sql = "SELECT t.*, 
               (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.ticket_id) as message_count 
        FROM support_tickets t 
        WHERE t.user_id = ? 
        ORDER BY 
            CASE 
                WHEN t.status = 'open' THEN 1
                WHEN t.status = 'in_progress' THEN 2
                WHEN t.status = 'waiting' THEN 3
                WHEN t.status = 'resolved' THEN 4
                WHEN t.status = 'closed' THEN 5
            END,
            t.updated_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $tickets[] = $row;
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Support Tickets')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .badge-status {
            min-width: 80px;
        }
        .priority-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        .priority-low {
            background-color: #0dcaf0;
        }
        .priority-medium {
            background-color: #ffc107;
        }
        .priority-high {
            background-color: #fd7e14;
        }
        .priority-critical {
            background-color: #dc3545;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- Start right Content here -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Support', 'title' => 'My Tickets')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <?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" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <?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" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">My Support Tickets</h5>
                                    <div>
                                        <a href="create_ticket.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom"></i> New Ticket
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($tickets)): ?>
                                        <div class="text-center py-4">
                                            <div class="avatar-md mx-auto mb-4">
                                                <div class="avatar-title bg-light text-primary rounded-circle fs-24">
                                                    <i class="ri-ticket-line"></i>
                                                </div>
                                            </div>
                                            <h5>No tickets found</h5>
                                            <p class="text-muted">You haven't created any support tickets yet.</p>
                                            <a href="create_ticket.php" class="btn btn-primary">Create New Ticket</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table align-middle table-nowrap mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th scope="col">Ref #</th>
                                                        <th scope="col">Subject</th>
                                                        <th scope="col">Category</th>
                                                        <th scope="col">Priority</th>
                                                        <th scope="col">Status</th>
                                                        <th scope="col">Created</th>
                                                        <th scope="col">Last Update</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($tickets as $ticket): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($ticket['reference_number']); ?></td>
                                                            <td>
                                                                <a href="view_ticket.php?id=<?php echo $ticket['ticket_id']; ?>" class="fw-medium">
                                                                    <?php echo htmlspecialchars($ticket['subject']); ?>
                                                                </a>
                                                                <p class="text-muted mb-0"><?php echo $ticket['message_count']; ?> messages</p>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($ticket['category']); ?></td>
                                                            <td>
                                                                <span class="priority-indicator priority-<?php echo $ticket['priority']; ?>"></span>
                                                                <?php echo ucfirst($ticket['priority']); ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_class = '';
                                                                switch ($ticket['status']) {
                                                                    case 'open':
                                                                        $status_class = 'bg-info';
                                                                        break;
                                                                    case 'in_progress':
                                                                        $status_class = 'bg-warning';
                                                                        break;
                                                                    case 'waiting':
                                                                        $status_class = 'bg-secondary';
                                                                        break;
                                                                    case 'resolved':
                                                                        $status_class = 'bg-success';
                                                                        break;
                                                                    case 'closed':
                                                                        $status_class = 'bg-dark';
                                                                        break;
                                                                }
                                                                ?>
                                                                <span class="badge badge-status <?php echo $status_class; ?>">
                                                                    <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($ticket['created_at'])); ?></td>
                                                            <td><?php echo date('M d, Y', strtotime($ticket['updated_at'])); ?></td>
                                                            <td>
                                                                <div class="hstack gap-2">
                                                                    <a href="view_ticket.php?id=<?php echo $ticket['ticket_id']; ?>" class="btn btn-sm btn-soft-primary">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                    <?php if ($ticket['status'] !== 'closed'): ?>
                                                                        <a href="update_ticket.php?id=<?php echo $ticket['ticket_id']; ?>&action=close" class="btn btn-sm btn-soft-danger">
                                                                            <i class="ri-close-line"></i>
                                                                        </a>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</body>
</html>