<?php
// This is the first line of ANY secure admin page.
require_once 'includes/auth_check.php';

// Set the current page for the sidebar active state
$page = 'tickets';

// Include your database and functions
require_once '../config/database.php';
require_once '../includes/functions.php';

// Generate CSRF token for secure operations
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Create a database connection
$database = new Database();
$db = $database->getConnection();

// Filter parameters
$status_filter = $_GET['status'] ?? 'all';
$priority_filter = $_GET['priority'] ?? 'all';
$search_query = $_GET['search'] ?? '';

// Build the query based on filters
$query = "
    SELECT t.*, 
           u.first_name, u.last_name, u.email,
           (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id) as message_count,
           (SELECT created_at FROM ticket_messages WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) as last_activity
    FROM tickets t 
    JOIN users u ON t.user_id = u.id 
    WHERE 1=1
";

$params = [];

if ($status_filter !== 'all') {
    $query .= " AND t.status = ?";
    $params[] = $status_filter;
}

if ($priority_filter !== 'all') {
    $query .= " AND t.priority = ?";
    $params[] = $priority_filter;
}

if (!empty($search_query)) {
    $query .= " AND (t.subject LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?)";
    $search_term = "%$search_query%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$query .= " ORDER BY 
    CASE 
        WHEN t.status = 'open' THEN 1 
        WHEN t.status = 'in_progress' THEN 2
        ELSE 3 
    END,
    CASE 
        WHEN t.priority = 'high' THEN 1
        WHEN t.priority = 'medium' THEN 2
        ELSE 3
    END,
    t.updated_at DESC";

try {
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get ticket counts for the dashboard
    $stmt = $db->prepare("SELECT status, COUNT(*) as count FROM tickets GROUP BY status");
    $stmt->execute();
    $ticket_counts = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $ticket_counts[$row['status']] = $row['count'];
    }
    $total_tickets = array_sum($ticket_counts);
    
    // Get priority counts for the chart
    $stmt = $db->prepare("SELECT priority, COUNT(*) as count FROM tickets GROUP BY priority");
    $stmt->execute();
    $priority_counts = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $priority_counts[$row['priority']] = $row['count'];
    }
    
} catch (PDOException $e) {
    $tickets = [];
    $ticket_counts = [];
    $total_tickets = 0;
    $priority_counts = [];
    $error_message = "Database error: " . $e->getMessage();
}

// Include the header for the admin page
include 'includes/header.php';
?>

<style>
/* Modern Ticket System Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --primary-dark: #4338ca;
    --secondary-color: #0ea5e9;
    --secondary-light: #e0f2fe;
    --success-color: #10b981;
    --success-light: #d1fae5;
    --warning-color: #f59e0b;
    --warning-light: #fef3c7;
    --danger-color: #ef4444;
    --danger-light: #fee2e2;
    --gray-50: #f9fafb;
    --gray-100: #f3f4f6;
    --gray-200: #e5e7eb;
    --gray-300: #d1d5db;
    --gray-400: #9ca3af;
    --gray-500: #6b7280;
    --gray-600: #4b5563;
    --gray-700: #374151;
    --gray-800: #1f2937;
    --gray-900: #111827;
    --border-radius: 0.5rem;
    --box-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);
    --box-shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
    --transition: all 0.2s ease;
}

/* Status and Priority Badges */
.status-badge, .priority-badge {
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 500;
}

.status-badge.open {
    background-color: var(--secondary-light);
    color: var(--secondary-color);
}

.status-badge.in_progress {
    background-color: var(--warning-light);
    color: var(--warning-color);
}

.status-badge.closed {
    background-color: var(--success-light);
    color: var(--success-color);
}

.priority-badge.high {
    background-color: var(--danger-light);
    color: var(--danger-color);
}

.priority-badge.medium {
    background-color: var(--warning-light);
    color: var(--warning-color);
}

.priority-badge.low {
    background-color: var(--gray-100);
    color: var(--gray-600);
}

/* User Info */
.user-info {
    display: flex;
    align-items: center;
}

.user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: var(--primary-light);
    color: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    margin-right: 0.75rem;
    flex-shrink: 0;
}

.user-name {
    font-weight: 500;
    color: var(--gray-800);
    margin: 0;
    line-height: 1.2;
}

.user-email {
    font-size: 0.75rem;
    color: var(--gray-500);
    margin: 0;
}

/* Search Box */
.search-box {
    position: relative;
}

.search-box i {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-500);
}

.search-box input {
    padding-left: 2.5rem;
    border-radius: 0.5rem;
}
</style>

<!-- Main Content Area -->
<?php if (isset($error_message)): ?>
    <div class="alert alert-danger"><?php echo $error_message; ?></div>
<?php endif; ?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">Support Tickets</h1>
    <div class="d-flex gap-2">
        <button type="button" class="btn btn-outline-secondary" id="refreshBtn">
            <i class='bx bx-refresh me-1'></i> Refresh
        </button>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newTicketModal">
            <i class='bx bx-plus me-1'></i> New Ticket
        </button>
    </div>
</div>

<!-- Stat Cards Row -->
<div class="row g-4">
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card">
            <div class="card-body">
                <div>
                    <h6 class="text-muted fw-normal mb-1">Total Tickets</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($total_tickets); ?></h3>
                </div>
                <div class="icon-circle bg-primary-light">
                    <i class='bx bx-list-ul'></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card">
            <div class="card-body">
                <div>
                    <h6 class="text-muted fw-normal mb-1">Open Tickets</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($ticket_counts['open'] ?? 0); ?></h3>
                </div>
                <div class="icon-circle bg-info-light" style="background-color: rgba(14, 165, 233, 0.1); color: #0ea5e9;">
                    <i class='bx bx-envelope-open'></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card">
            <div class="card-body">
                <div>
                    <h6 class="text-muted fw-normal mb-1">In Progress</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($ticket_counts['in_progress'] ?? 0); ?></h3>
                </div>
                <div class="icon-circle bg-warning-light">
                    <i class='bx bx-time'></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card">
            <div class="card-body">
                <div>
                    <h6 class="text-muted fw-normal mb-1">High Priority</h6>
                    <h3 class="mb-0 fw-bold"><?php echo number_format($priority_counts['high'] ?? 0); ?></h3>
                </div>
                <div class="icon-circle bg-danger-light">
                    <i class='bx bx-shield-quarter'></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters Section -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="card-title">Filter Tickets</h5>
    </div>
    <div class="card-body">
        <form method="GET" action="tickets.php">
            <div class="row g-3">
                <div class="col-md-5">
                    <div class="search-box">
                        <i class='bx bx-search'></i>
                        <input type="text" class="form-control" name="search" placeholder="Search tickets..." value="<?php echo htmlspecialchars($search_query); ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="status" name="status">
                        <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Statuses</option>
                        <option value="open" <?php echo $status_filter === 'open' ? 'selected' : ''; ?>>Open</option>
                        <option value="in_progress" <?php echo $status_filter === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                        <option value="closed" <?php echo $status_filter === 'closed' ? 'selected' : ''; ?>>Closed</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="priority" name="priority">
                        <option value="all" <?php echo $priority_filter === 'all' ? 'selected' : ''; ?>>All Priorities</option>
                        <option value="high" <?php echo $priority_filter === 'high' ? 'selected' : ''; ?>>High</option>
                        <option value="medium" <?php echo $priority_filter === 'medium' ? 'selected' : ''; ?>>Medium</option>
                        <option value="low" <?php echo $priority_filter === 'low' ? 'selected' : ''; ?>>Low</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Tickets Table -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="card-title">All Tickets</h5>
    </div>
    <div class="card-body p-0">
        <?php if (empty($tickets)): ?>
            <div class="text-center py-5">
                <i class='bx bx-support' style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3">No Tickets Found</h5>
                <p class="text-muted">There are no tickets matching your filters. Try adjusting your search criteria or create a new ticket.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4">Subject</th>
                            <th>Status</th>
                            <th>Priority</th>
                            <th>Customer</th>
                            <th>Last Activity</th>
                            <th class="text-end pe-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($tickets as $ticket): ?>
                            <tr>
                                <td class="ps-4">
                                    <a href="ticket_details.php?id=<?php echo $ticket['id']; ?>" class="fw-medium text-decoration-none text-dark">
                                        <?php echo htmlspecialchars($ticket['subject']); ?>
                                    </a>
                                    <div class="text-muted small">
                                        <i class='bx bx-message-detail'></i> <?php echo $ticket['message_count']; ?> messages
                                    </div>
                                </td>
                                <td>
                                    <span class="status-badge <?php echo $ticket['status']; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="priority-badge <?php echo $ticket['priority']; ?>">
                                        <?php echo ucfirst($ticket['priority']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="icon-circle bg-primary-light me-2" style="width: 32px; height: 32px; font-size: 0.875rem;">
                                            <?php echo strtoupper(substr($ticket['first_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="fw-medium"><?php echo htmlspecialchars($ticket['first_name'] . ' ' . $ticket['last_name']); ?></div>
                                            <small class="text-muted"><?php echo htmlspecialchars($ticket['email']); ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div>
                                        <?php echo date('M j, Y', strtotime($ticket['last_activity'] ?? $ticket['created_at'])); ?>
                                        <div class="small text-muted">
                                            <?php echo date('g:i A', strtotime($ticket['last_activity'] ?? $ticket['created_at'])); ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-end pe-4">
                                    <div class="d-flex justify-content-end">
                                        <a href="ticket_details.php?id=<?php echo $ticket['id']; ?>" class="btn btn-sm btn-outline-primary me-2">
                                            View
                                        </a>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                Action
                                            </button>
                                        <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="update_ticket_status.php?id=<?php echo $ticket['id']; ?>&status=open">Mark as Open</a></li>
    <li><a class="dropdown-item" href="update_ticket_status.php?id=<?php echo $ticket['id']; ?>&status=in_progress">Mark as In Progress</a></li>
    <li><a class="dropdown-item" href="update_ticket_status.php?id=<?php echo $ticket['id']; ?>&status=closed">Mark as Closed</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item text-danger delete-ticket" href="#" data-id="<?php echo $ticket['id']; ?>" data-subject="<?php echo htmlspecialchars($ticket['subject']); ?>">Delete Ticket</a></li>
</ul>

                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
    <?php if (!empty($tickets)): ?>
        <div class="card-footer text-center bg-light">
            <a href="#" class="fw-bold">View All Tickets →</a>
        </div>
    <?php endif; ?>
</div>

<!-- New Ticket Modal -->
<div class="modal fade" id="newTicketModal" tabindex="-1" aria-labelledby="newTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newTicketModalLabel">Create New Ticket</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="create_ticket.php" method="POST">
                <div class="modal-body">
                    <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="row mb-3">
                        <div class="col-md-6">
                            <label for="user_id" class="form-label">Customer</label>
                            <select class="form-select" id="user_id" name="user_id" required>
                                <option value="">Select Customer</option>
                                <?php
                                // Get all users
                                try {
                                    $stmt = $db->prepare("SELECT id, first_name, last_name, email FROM users ORDER BY first_name, last_name");
                                    $stmt->execute();
                                    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    foreach ($users as $user):
                                    ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name'] . ' (' . $user['email'] . ')'); ?>
                                    </option>
                                    <?php endforeach;
                                } catch (PDOException $e) {
                                    // Handle error silently
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="priority" class="form-label">Priority</label>
                            <select class="form-select" id="priority" name="priority" required>
                                <option value="low">Low</option>
                                <option value="medium" selected>Medium</option>
                                <option value="high">High</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="message" class="form-label">Initial Message</label>
                        <textarea class="form-control" id="message" name="message" rows="5" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Ticket</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Refresh button functionality
    document.getElementById('refreshBtn').addEventListener('click', function() {
        window.location.reload();
    });
    
    // Auto-submit form when status or priority changes
    document.getElementById('status').addEventListener('change', function() {
        this.form.submit();
    });
    
    document.getElementById('priority').addEventListener('change', function() {
        this.form.submit();
    });
});

// Delete ticket confirmation
document.querySelectorAll('.delete-ticket').forEach(function(element) {
    element.addEventListener('click', function(e) {
        e.preventDefault();
        const ticketId = this.getAttribute('data-id');
        const ticketSubject = this.getAttribute('data-subject');
        
        Swal.fire({
            title: 'Are you sure?',
            html: `You are about to delete ticket #${ticketId}: <strong>${ticketSubject}</strong><br><br>This action cannot be undone and all ticket messages will be permanently deleted.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `delete_ticket.php?id=${ticketId}&csrf_token=<?php echo $_SESSION['csrf_token']; ?>`;
            }
        });
    });
});

</script>

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