<?php session_start();
// bank_linking.php
include 'includes/head.php';

// Get filter parameters
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$category_filter = isset($_GET['category']) ? $conn->real_escape_string($_GET['category']) : '';
$priority_filter = isset($_GET['priority']) ? $conn->real_escape_string($_GET['priority']) : '';

// Build query with filters
$where_conditions = array("user_id = '$user_id'");
if (!empty($status_filter)) {
    $where_conditions[] = "status = '$status_filter'";
}
if (!empty($category_filter)) {
    $where_conditions[] = "category = '$category_filter'";
}
if (!empty($priority_filter)) {
    $where_conditions[] = "priority = '$priority_filter'";
}

$where_clause = implode(' AND ', $where_conditions);

// Get pagination parameters
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM support_tickets WHERE $where_clause";
$count_result = mysqli_query($conn, $count_sql);
$total_tickets = mysqli_fetch_assoc($count_result)['total'];
$total_pages = ceil($total_tickets / $per_page);

// Get tickets with pagination
$tickets_sql = "SELECT * FROM support_tickets 
                WHERE $where_clause 
                ORDER BY created_at DESC 
                LIMIT $offset, $per_page";
$tickets_result = mysqli_query($conn, $tickets_sql);

// Get ticket statistics
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open_tickets,
    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress_tickets,
    SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved_tickets,
    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_tickets
    FROM support_tickets 
    WHERE user_id = '$user_id'";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Support Tickets - E-Finance Loans</title>
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" sizes="16x16" href="images/favicon.png">
    <!-- Custom Stylesheet -->
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="vendor/toastr/toastr.min.css">
    <style>
    .ticket-card {
        border: none;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        margin-bottom: 15px;
    }
    .ticket-card:hover {
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        transform: translateY(-2px);
    }
    .status-badge {
        font-size: 0.75em;
        padding: 4px 8px;
    }
    .priority-badge {
        font-size: 0.7em;
        padding: 3px 6px;
    }
    .ticket-excerpt {
        color: #666;
        font-size: 0.9em;
        line-height: 1.4;
    }
    .filter-active {
        background-color: #007bff !important;
        color: white !important;
    }
    .stat-card {
        text-align: center;
        padding: 20px;
        border-radius: 10px;
        color: white;
        margin-bottom: 20px;
    }
    .stat-open { background: linear-gradient(135deg, #ff6b6b, #ee5a24); }
    .stat-progress { background: linear-gradient(135deg, #feca57, #ff9ff3); }
    .stat-resolved { background: linear-gradient(135deg, #48dbfb, #0abde3); }
    .stat-closed { background: linear-gradient(135deg, #1dd1a1, #10ac84); }
    .pagination .page-link { color: #007bff; }
    .pagination .page-item.active .page-link {
        background-color: #007bff;
        border-color: #007bff;
    }
    </style>
</head>

<body class="dashboard">
    <div id="main-wrapper">
        
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>My Support Tickets</h3>
                                        <p class="mb-2">Manage and track your support requests</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="support.php">Support</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">My Tickets</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Ticket Statistics -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-open">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-clock fs-1"></i>
                            </div>
                            <h4 class="mb-1"><?php echo $stats['open_tickets']; ?></h4>
                            <p class="mb-0">Open Tickets</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-progress">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-refresh fs-1"></i>
                            </div>
                            <h4 class="mb-1"><?php echo $stats['in_progress_tickets']; ?></h4>
                            <p class="mb-0">In Progress</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-resolved">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-check fs-1"></i>
                            </div>
                            <h4 class="mb-1"><?php echo $stats['resolved_tickets']; ?></h4>
                            <p class="mb-0">Resolved</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-closed">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-archive fs-1"></i>
                            </div>
                            <h4 class="mb-1"><?php echo $stats['closed_tickets']; ?></h4>
                            <p class="mb-0">Closed</p>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-xl-12">
                        <!-- Filters Card -->
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">Filter Tickets</h5>
                                <div>
                                    <a href="create_ticket.php" class="btn btn-primary btn-sm me-2">
                                        <i class="fi fi-rr-plus me-1"></i>New Ticket
                                    </a>
                                    <a href="tickets.php" class="btn btn-outline-secondary btn-sm">Clear Filters</a>
                                </div>
                            </div>
                            <div class="card-body">
                                <form method="GET" action="tickets.php" class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="">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="resolved" <?php echo $status_filter == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                                            <option value="closed" <?php echo $status_filter == 'closed' ? 'selected' : ''; ?>>Closed</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Category</label>
                                        <select class="form-select" name="category">
                                            <option value="">All Categories</option>
                                            <option value="loan_application" <?php echo $category_filter == 'loan_application' ? 'selected' : ''; ?>>Loan Application</option>
                                            <option value="repayment" <?php echo $category_filter == 'repayment' ? 'selected' : ''; ?>>Repayment</option>
                                            <option value="account" <?php echo $category_filter == 'account' ? 'selected' : ''; ?>>Account</option>
                                            <option value="technical" <?php echo $category_filter == 'technical' ? 'selected' : ''; ?>>Technical</option>
                                            <option value="dispute" <?php echo $category_filter == 'dispute' ? 'selected' : ''; ?>>Dispute</option>
                                            <option value="general" <?php echo $category_filter == 'general' ? 'selected' : ''; ?>>General</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Priority</label>
                                        <select class="form-select" name="priority">
                                            <option value="">All Priorities</option>
                                            <option value="low" <?php echo $priority_filter == 'low' ? 'selected' : ''; ?>>Low</option>
                                            <option value="medium" <?php echo $priority_filter == 'medium' ? 'selected' : ''; ?>>Medium</option>
                                            <option value="high" <?php echo $priority_filter == 'high' ? 'selected' : ''; ?>>High</option>
                                            <option value="urgent" <?php echo $priority_filter == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fi fi-rr-filter me-1"></i>Apply Filters
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Tickets List -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    Support Tickets 
                                    <span class="badge bg-primary"><?php echo $total_tickets; ?></span>
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if(mysqli_num_rows($tickets_result) > 0): ?>
                                    <div class="tickets-list">
                                        <?php while($ticket = mysqli_fetch_assoc($tickets_result)): 
                                            // Determine status badge class
                                            $status_class = '';
                                            if($ticket['status'] == 'open') $status_class = 'bg-warning';
                                            elseif($ticket['status'] == 'in_progress') $status_class = 'bg-info';
                                            elseif($ticket['status'] == 'resolved') $status_class = 'bg-success';
                                            else $status_class = 'bg-secondary';
                                            
                                            // Determine priority badge class
                                            $priority_class = '';
                                            if($ticket['priority'] == 'urgent') $priority_class = 'bg-danger';
                                            elseif($ticket['priority'] == 'high') $priority_class = 'bg-warning';
                                            elseif($ticket['priority'] == 'medium') $priority_class = 'bg-primary';
                                            else $priority_class = 'bg-secondary';
                                            
                                            // Format category
                                            $category_display = ucfirst(str_replace('_', ' ', $ticket['category']));
                                            
                                            // Create excerpt
                                            $excerpt = strlen($ticket['description']) > 150 ? 
                                                substr($ticket['description'], 0, 150) . '...' : 
                                                $ticket['description'];
                                        ?>
                                        <a href="ticket_details.php?id=<?php echo $ticket['id']; ?>" class="card ticket-card">
                                            <div class="card-body">
                                                <div class="row align-items-center">
                                                    <div class="col-md-8">
                                                        <div class="d-flex align-items-start mb-2">
                                                            <h6 class="mb-0 me-3"><?php echo htmlspecialchars($ticket['subject']); ?></h6>
                                                            <span class="badge <?php echo $status_class; ?> status-badge">
                                                                <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                                            </span>
                                                        </div>
                                                        <p class="ticket-excerpt mb-2"><?php echo htmlspecialchars($excerpt); ?></p>
                                                        <div class="d-flex gap-3">
                                                            <small class="text-muted">
                                                                <i class="fi fi-rr-folder me-1"></i>
                                                                <?php echo $category_display; ?>
                                                            </small>
                                                            <small class="text-muted">
                                                                <i class="fi fi-rr-calendar me-1"></i>
                                                                <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?>
                                                            </small>
                                                            <small class="text-muted">
                                                                <i class="fi fi-rr-ticket me-1"></i>
                                                                <?php echo $ticket['ticket_number']; ?>
                                                            </small>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4 text-end">
                                                        <div class="mb-2">
                                                            <span class="badge <?php echo $priority_class; ?> priority-badge">
                                                                <?php echo ucfirst($ticket['priority']); ?> Priority
                                                            </span>
                                                        </div>
                                                        <div class="text-muted">
                                                            <small>Last updated: <?php echo date('M j', strtotime($ticket['updated_at'])); ?></small>
                                                        </div>
                                                        <i class="fi fi-rr-arrow-right text-primary mt-2"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </a>
                                        <?php endwhile; ?>
                                    </div>

                                    <!-- Pagination -->
                                    <?php if($total_pages > 1): ?>
                                    <nav aria-label="Ticket pagination" class="mt-4">
                                        <ul class="pagination justify-content-center">
                                            <?php if($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page - 1))); ?>">
                                                    Previous
                                                </a>
                                            </li>
                                            <?php endif; ?>

                                            <?php for($i = 1; $i <= $total_pages; $i++): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $i))); ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                            <?php endfor; ?>

                                            <?php if($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page + 1))); ?>">
                                                    Next
                                                </a>
                                            </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                    <?php endif; ?>

                                <?php else: ?>
                                    <div class="text-center py-5">
                                        <i class="fi fi-rr-inbox fs-1 text-muted mb-3"></i>
                                        <h5 class="text-muted">No tickets found</h5>
                                        <p class="text-muted mb-4">
                                            <?php echo ($status_filter || $category_filter || $priority_filter) ? 
                                                'Try adjusting your filters' : 
                                                'You haven\'t created any support tickets yet'; ?>
                                        </p>
                                        <a href="create_ticket.php" class="btn btn-primary">
                                            <i class="fi fi-rr-plus me-2"></i>Create Your First Ticket
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Auto-submit search form when typing stops
    let searchTimeout;
    document.querySelector('input[name="search"]').addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            document.getElementById('searchForm').submit();
        }, 1000);
    });

    // Quick filter buttons
    function quickFilter(filter, value) {
        window.location.href = `tickets.php?${filter}=${value}`;
    }
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>