<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

$error = '';
$success = '';

// Create new ticket
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_ticket'])) {
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $category = $_POST['category'] ?? 'general';
    
    if (empty($subject) || empty($message)) {
        $error = 'Please fill in all required fields.';
    } else {
        $ticketNumber = generateTicketNumber();
        $stmt = $db->prepare("INSERT INTO support_tickets (ticket_number, user_id, subject, message, category, status) VALUES (?, ?, ?, ?, ?, 'open')");
        $stmt->bind_param('sisss', $ticketNumber, $user['id'], $subject, $message, $category);
        
        if ($stmt->execute()) {
            $success = 'Ticket created successfully! Ticket number: ' . $ticketNumber;
            createNotification($user['id'], 'Support Ticket Created', 'Your ticket ' . $ticketNumber . ' has been submitted. We will respond shortly.', 'info');
        } else {
            $error = 'Failed to create ticket. Please try again.';
        }
    }
}

// Get user's tickets
$stmt = $db->prepare("SELECT t.*, COUNT(r.id) as reply_count FROM support_tickets t LEFT JOIN ticket_replies r ON t.id = r.ticket_id WHERE t.user_id = ? GROUP BY t.id ORDER BY t.created_at DESC");
$stmt->bind_param('i', $user['id']);
$stmt->execute();
$tickets = $stmt->get_result();

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Center - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger fade-in"><span>⚠</span> <?php echo e($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success fade-in"><span>✓</span> <?php echo e($success); ?></div>
            <?php endif; ?>
            
            <!-- New Ticket Form -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">Create New Ticket</span>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <input type="hidden" name="create_ticket" value="1">
                        <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 20px;">
                            <div class="form-group">
                                <label class="form-label">Category *</label>
                                <select name="category" class="form-control" required>
                                    <option value="general">General Inquiry</option>
                                    <option value="account">Account Issues</option>
                                    <option value="transaction">Transaction Problems</option>
                                    <option value="card">Card Issues</option>
                                    <option value="technical">Technical Support</option>
                                    <option value="billing">Billing</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Subject *</label>
                                <input type="text" name="subject" class="form-control" required placeholder="Brief description of your issue">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Message *</label>
                            <textarea name="message" class="form-control" rows="4" required placeholder="Please describe your issue in detail..."></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Submit Ticket</button>
                    </form>
                </div>
            </div>
            
            <!-- Tickets List -->
            <div class="card">
                <div class="card-header">
                    <span class="card-title">My Tickets</span>
                </div>
                <div class="card-body" style="padding: 0;">
                    <?php if ($tickets->num_rows > 0): ?>
                        <div class="table-container">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Ticket #</th>
                                        <th>Subject</th>
                                        <th>Category</th>
                                        <th>Status</th>
                                        <th>Priority</th>
                                        <th>Replies</th>
                                        <th>Created</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($ticket = $tickets->fetch_assoc()): ?>
                                        <tr>
                                            <td><code style="font-size: 12px; color: var(--primary); font-weight: 700;"><?php echo e($ticket['ticket_number']); ?></code></td>
                                            <td><?php echo e($ticket['subject']); ?></td>
                                            <td><span style="text-transform: capitalize;"><?php echo e($ticket['category']); ?></span></td>
                                            <td>
                                                <span class="status-badge <?php 
                                                    echo $ticket['status'] === 'open' ? 'info' : 
                                                        ($ticket['status'] === 'resolved' ? 'success' : 
                                                        ($ticket['status'] === 'closed' ? 'secondary' : 'warning')); 
                                                ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($ticket['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="status-badge <?php 
                                                    echo $ticket['priority'] === 'critical' ? 'danger' : 
                                                        ($ticket['priority'] === 'high' ? 'warning' : 
                                                        ($ticket['priority'] === 'medium' ? 'info' : 'secondary')); 
                                                ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($ticket['priority'])); ?>
                                                </span>
                                            </td>
                                            <td style="text-align: center;"><?php echo $ticket['reply_count']; ?></td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($ticket['created_at']); ?></td>
                                            <td>
                                                <a href="ticket.php?id=<?php echo $ticket['id']; ?>" class="btn btn-sm btn-outline-primary">View</a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state" style="padding: 40px;">
                            <div class="empty-state-icon">🎫</div>
                            <h3>No Tickets Yet</h3>
                            <p>You haven't created any support tickets. Use the form above to get help.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>
