<?php
/**
 * User - Enhanced Support Tickets
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'Support Tickets';
$user_id = $_SESSION['user_id'];

$tickets = [];
try {
    // Check if support_tickets table exists
    $table_check = db()->query("SHOW TABLES LIKE 'support_tickets'");
    if ($table_check->rowCount() > 0) {
        $stmt = db()->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$user_id]);
        $tickets = $stmt->fetchAll();
    } else {
        error_log("Support tickets table does not exist for user");
    }
} catch (PDOException $e) {
    error_log("User tickets query error: " . $e->getMessage());
}

// Calculate stats
$stats = ['open' => 0, 'in_progress' => 0, 'resolved' => 0, 'closed' => 0];
foreach ($tickets as $ticket) {
    if (isset($stats[$ticket['status']])) {
        $stats[$ticket['status']]++;
    }
}
$total_tickets = count($tickets);
$open_tickets = $stats['open'] + $stats['in_progress'];

include __DIR__ . '/includes/header.php';
?>

<style>
.ticket-card {
    border: none;
    border-radius: 16px;
    transition: all 0.3s ease;
    background: #fff;
}
.ticket-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 24px rgba(0,0,0,0.1) !important;
}
.status-open { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); color: #dc2626; }
.status-in_progress { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); color: #d97706; }
.status-resolved { background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); color: #059669; }
.status-closed { background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%); color: #4b5563; }

.priority-badge {
    font-size: 0.7rem;
    padding: 0.25rem 0.75rem;
    border-radius: 50px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.priority-urgent { background: #fee2e2; color: #dc2626; }
.priority-high { background: #ffedd5; color: #ea580c; }
.priority-medium { background: #fff7ed; color: #f97316; }
.priority-low { background: #f3f4f6; color: #4b5563; }

.ticket-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}
.empty-state {
    text-align: center;
    padding: 4rem 2rem;
}
.empty-state-icon {
    width: 120px;
    height: 120px;
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1.5rem;
}
.stat-card {
    border: none;
    border-radius: 16px;
    padding: 1.5rem;
    text-align: center;
}
.stat-card.open { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); }
.stat-card.in_progress { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); }
.stat-card.resolved { background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); }
.stat-card.total { background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%); }

.ticket-number {
    font-family: 'Courier New', monospace;
    font-weight: 700;
    letter-spacing: 1px;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold mb-1">Support Tickets</h2>
        <p class="text-muted mb-0">Manage your support requests and track their status</p>
    </div>
    <a href="create-ticket.php" class="btn btn-primary btn-lg">
        <i class="bi bi-plus-circle me-2"></i>Create Ticket
    </a>
</div>

<?php if (!empty($tickets)): ?>
<!-- Stats Row -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="stat-card total">
            <h3 class="fw-bold mb-1 text-primary"><?php echo $total_tickets; ?></h3>
            <small class="text-muted fw-medium">Total Tickets</small>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card open">
            <h3 class="fw-bold mb-1 text-danger"><?php echo $stats['open']; ?></h3>
            <small class="text-muted fw-medium">Open</small>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card in_progress">
            <h3 class="fw-bold mb-1 text-warning"><?php echo $stats['in_progress']; ?></h3>
            <small class="text-muted fw-medium">In Progress</small>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card resolved">
            <h3 class="fw-bold mb-1 text-success"><?php echo $stats['resolved'] + $stats['closed']; ?></h3>
            <small class="text-muted fw-medium">Resolved</small>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (empty($tickets)): ?>
<!-- Empty State -->
<div class="card border-0 shadow-sm">
    <div class="empty-state">
        <div class="empty-state-icon">
            <i class="bi bi-headset text-warning" style="font-size: 3rem;"></i>
        </div>
        <h3 class="fw-bold mb-2">No Tickets Yet</h3>
        <p class="text-muted mb-4">You haven't created any support tickets. Our team is ready to help you with any questions or issues.</p>
        <a href="create-ticket.php" class="btn btn-primary btn-lg">
            <i class="bi bi-plus-circle me-2"></i>Create Your First Ticket
        </a>
    </div>
</div>

<!-- Quick Help Cards -->
<div class="row g-4 mt-4">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 64px; height: 64px;">
                    <i class="bi bi-question-circle fs-3"></i>
                </div>
                <h5 class="fw-bold">FAQs</h5>
                <p class="text-muted small">Find answers to commonly asked questions</p>
                <a href="<?php echo BASE_URL; ?>support.php" class="btn btn-outline-primary btn-sm">View FAQs</a>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="bg-success bg-opacity-10 text-success rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 64px; height: 64px;">
                    <i class="bi bi-whatsapp fs-3"></i>
                </div>
                <h5 class="fw-bold">WhatsApp</h5>
                <p class="text-muted small">Get quick help via WhatsApp</p>
                <a href="https://wa.me/916388758325" target="_blank" class="btn btn-outline-success btn-sm">Chat Now</a>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="bg-info bg-opacity-10 text-info rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 64px; height: 64px;">
                    <i class="bi bi-envelope fs-3"></i>
                </div>
                <h5 class="fw-bold">Email Us</h5>
                <p class="text-muted small">Send us an email anytime</p>
                <a href="mailto:support@hostxolo.com" class="btn btn-outline-info btn-sm">Send Email</a>
            </div>
        </div>
    </div>
</div>
<?php else: ?>
<!-- Tickets Grid -->
<div class="row g-4">
    <?php foreach ($tickets as $ticket): 
        $status_class = 'status-' . $ticket['status'];
        $priority_class = 'priority-' . $ticket['priority'];
        
        // Determine icon based on status
        $status_icon = match($ticket['status']) {
            'open' => 'bi-envelope-open',
            'in_progress' => 'bi-arrow-repeat',
            'resolved' => 'bi-check-circle',
            'closed' => 'bi-archive',
            default => 'bi-ticket'
        };
    ?>
    <div class="col-md-6 col-xl-4">
        <div class="card ticket-card shadow-sm h-100">
            <div class="card-body p-4">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-start mb-3">
                    <div class="ticket-icon <?php echo $status_class; ?>">
                        <i class="bi <?php echo $status_icon; ?>"></i>
                    </div>
                    <span class="priority-badge <?php echo $priority_class; ?>">
                        <?php echo $ticket['priority']; ?>
                    </span>
                </div>
                
                <!-- Ticket Number & Status -->
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="ticket-number text-muted">#<?php echo $ticket['ticket_number']; ?></span>
                    <span class="badge rounded-pill <?php echo $status_class; ?> px-3 py-2">
                        <i class="bi bi-circle-fill small me-1"></i>
                        <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                    </span>
                </div>
                
                <!-- Subject -->
                <h5 class="fw-bold mb-3"><?php echo substr($ticket['subject'], 0, 50); ?><?php echo strlen($ticket['subject']) > 50 ? '...' : ''; ?></h5>
                
                <!-- Category -->
                <div class="mb-3">
                    <span class="badge bg-light text-dark border">
                        <i class="bi bi-folder me-1"></i><?php echo ucfirst($ticket['category'] ?? 'general'); ?>
                    </span>
                </div>
                
                <!-- Footer Info -->
                <div class="d-flex justify-content-between align-items-center text-muted small mb-3">
                    <span><i class="bi bi-calendar me-1"></i><?php echo format_date($ticket['created_at']); ?></span>
                    <span><i class="bi bi-clock me-1"></i><?php echo time_ago($ticket['created_at']); ?></span>
                </div>
                
                <!-- Action Button -->
                <a href="ticket-view.php?id=<?php echo $ticket['id']; ?>" class="btn btn-outline-primary w-100">
                    <i class="bi bi-eye me-2"></i>View Details
                </a>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Contact Support Banner -->
<div class="card border-0 shadow-sm mt-4 bg-primary text-white">
    <div class="card-body p-4">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h5 class="fw-bold mb-2"><i class="bi bi-lightning-charge me-2"></i>Need Urgent Help?</h5>
                <p class="opacity-90 mb-0">For critical issues, reach out directly via WhatsApp for fastest response.</p>
            </div>
            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                <a href="https://wa.me/916388758325" target="_blank" class="btn btn-light">
                    <i class="bi bi-whatsapp me-2"></i>WhatsApp Us
                </a>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php 
// Helper function for time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff / 60) . ' min ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
    if ($diff < 604800) return floor($diff / 86400) . ' days ago';
    return floor($diff / 604800) . ' weeks ago';
}

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