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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

// Search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$customer_type_filter = isset($_GET['customer_type']) ? $_GET['customer_type'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'registration_date';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 25;
$offset = ($page - 1) * $per_page;

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(c.first_name LIKE ? OR c.last_name LIKE ? OR c.customer_code LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
    $param_types .= 'sssss';
}

if (!empty($customer_type_filter)) {
    $where_conditions[] = "c.customer_type = ?";
    $params[] = $customer_type_filter;
    $param_types .= 's';
}

if (!empty($status_filter)) {
    $where_conditions[] = "c.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Valid sort columns
$valid_sorts = ['created_at', 'first_name', 'last_name', 'customer_code', 'total_orders', 'total_spent', 'last_order_date'];
if (!in_array($sort, $valid_sorts)) {
    $sort = 'created_at';
}

$valid_orders = ['ASC', 'DESC'];
if (!in_array($order, $valid_orders)) {
    $order = 'DESC';
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM customers c $where_clause";
if (!empty($params)) {
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param($param_types, ...$params);
    $count_stmt->execute();
    $total_customers = $count_stmt->get_result()->fetch_assoc()['total'];
} else {
    $total_customers = $conn->query($count_sql)->fetch_assoc()['total'];
}

$total_pages = ceil($total_customers / $per_page);

// Fetch customers
$sql = "SELECT c.*, u.full_name as created_by_name
        FROM customers c
        LEFT JOIN users u ON c.created_by = u.user_id
        $where_clause
        ORDER BY c.$sort $order
        LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$customers = $stmt->get_result();

// Get summary statistics
$stats_sql = "SELECT 
    COUNT(*) as total_customers,
    SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_customers,
    SUM(CASE WHEN customer_type = 'INDIVIDUAL' THEN 1 ELSE 0 END) as vip_customers,
    SUM(CASE WHEN customer_type = 'CORPORATE' THEN 1 ELSE 0 END) as corporate_customers
   
    FROM customers c $where_clause";

if (!empty($where_conditions)) {
    // Remove the LIMIT parameters for stats
    $stats_params = array_slice($params, 0, -2);
    $stats_param_types = substr($param_types, 0, -2);
    $stats_stmt = $conn->prepare($stats_sql);
    $stats_stmt->bind_param($stats_param_types, ...$stats_params);
    $stats_stmt->execute();
    $stats = $stats_stmt->get_result()->fetch_assoc();
} else {
    $stats = $conn->query($stats_sql)->fetch_assoc();
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer List - Laundry Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .filters-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
            position: sticky;
            top: 0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .customer-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f1f5f9; color: #64748b; }
        .status-blocked { background: #fee2e2; color: #991b1b; }
        
        .customer-regular { background: #f1f5f9; color: #64748b; }
        .customer-vip { background: #fef3c7; color: #92400e; }
        .customer-corporate { background: #dbeafe; color: #1d4ed8; }
        
        .btn-primary {
            background: #3b82f6;
            border: 1px solid #3b82f6;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            border-color: #1d4ed8;
            color: white;
        }
        
        .btn-secondary {
            background: #6b7280;
            border: 1px solid #6b7280;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
            border-color: #4b5563;
            color: white;
        }
        
        .btn-outline {
            background: transparent;
            border: 1px solid #d1d5db;
            color: #374151;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-block;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .btn-outline:hover {
            background: #f9fafb;
            border-color: #9ca3af;
            color: #374151;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.5rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
            margin-top: 2rem;
        }
        
        .pagination a,
        .pagination span {
            padding: 0.5rem 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            text-decoration: none;
            color: #374151;
            font-size: 0.875rem;
        }
        
        .pagination a:hover {
            background: #f9fafb;
        }
        
        .pagination .current {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        .d-flex { display: flex; }
        .justify-content-between { justify-content: space-between; }
        .align-items-center { align-items: center; }
        .me-2 { margin-right: 0.5rem; }
        .me-3 { margin-right: 1rem; }
        .mb-0 { margin-bottom: 0; }
        .mb-3 { margin-bottom: 1rem; }
        .text-muted { color: #64748b; }
        .fw-bold { font-weight: 600; }
        
        .sortable {
            cursor: pointer;
            user-select: none;
        }
        
        .sortable:hover {
            background: #f1f5f9;
        }
        
        .sort-icon {
            margin-left: 0.25rem;
            font-size: 0.75rem;
            color: #9ca3af;
        }
        
        @media (max-width: 768px) {
            .table-card {
                overflow-x: auto;
            }
            
            .filters-card .row {
                flex-direction: column;
            }
            
            .filters-card .col-md-3,
            .filters-card .col-md-2 {
                width: 100%;
                margin-bottom: 1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h4 class="mb-0">Customer Management</h4>
                            <p class="text-muted mb-0">Manage all customer information</p>
                        </div>
                        <a href="register_customer.php" class="btn-primary">
                            <i class="ph-user-plus me-2"></i>Add New Customer
                        </a>
                    </div>

                    <!-- Statistics -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['total_customers']); ?></div>
                            <div class="stat-label">Total Customers</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['active_customers']); ?></div>
                            <div class="stat-label">Active Customers</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['vip_customers']); ?></div>
                            <div class="stat-label">VIP Customers</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['corporate_customers']); ?></div>
                            <div class="stat-label">Corporate Customers</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KSh <?php echo number_format($stats['total_revenue']); ?></div>
                            <div class="stat-label">Total Revenue</div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filters-card">
                        <form method="GET" class="row align-items-end">
                            <div class="col-md-3">
                                <label class="form-label">Search Customers</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Name, code, phone, email...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Customer Type</label>
                                <select class="form-control" name="customer_type">
                                    <option value="">All Types</option>
                                    <option value="Regular" <?php echo $customer_type_filter === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                                    <option value="VIP" <?php echo $customer_type_filter === 'VIP' ? 'selected' : ''; ?>>VIP</option>
                                    <option value="Corporate" <?php echo $customer_type_filter === 'Corporate' ? 'selected' : ''; ?>>Corporate</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-control" name="status">
                                    <option value="">All Status</option>
                                    <option value="ACTIVE" <?php echo $status_filter === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                    <option value="INACTIVE" <?php echo $status_filter === 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                    <option value="BLOCKED" <?php echo $status_filter === 'BLOCKED' ? 'selected' : ''; ?>>Blocked</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Sort By</label>
                                <select class="form-control" name="sort">
                                    <option value="registration_date" <?php echo $sort === 'registration_date' ? 'selected' : ''; ?>>Registration Date</option>
                                    <option value="first_name" <?php echo $sort === 'first_name' ? 'selected' : ''; ?>>First Name</option>
                                    <option value="last_name" <?php echo $sort === 'last_name' ? 'selected' : ''; ?>>Last Name</option>
                                    <option value="total_orders" <?php echo $sort === 'total_orders' ? 'selected' : ''; ?>>Total Orders</option>
                                    <option value="total_spent" <?php echo $sort === 'total_spent' ? 'selected' : ''; ?>>Total Spent</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Order</label>
                                <select class="form-control" name="order">
                                    <option value="DESC" <?php echo $order === 'DESC' ? 'selected' : ''; ?>>Descending</option>
                                    <option value="ASC" <?php echo $order === 'ASC' ? 'selected' : ''; ?>>Ascending</option>
                                </select>
                            </div>
                            <div class="col-md-1">
                                <button type="submit" class="btn-primary w-100">
                                    <i class="ph-magnifying-glass"></i>
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Customers Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">
                                Customers (<?php echo number_format($total_customers); ?> total)
                            </h3>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Orders</th>
                                    <th>Total Spent</th>
                                    <th>Loyalty Points</th>
                                    <th>Last Order</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($customers->num_rows > 0): ?>
                                    <?php while ($customer = $customers->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="customer-avatar me-3">
                                                    <?php echo strtoupper(substr($customer['first_name'], 0, 1) . substr($customer['last_name'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <div class="fw-bold"><?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?></div>
                                                    <div class="text-muted" style="font-size: 0.75rem;"><?php echo htmlspecialchars($customer['customer_code']); ?></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div><?php echo htmlspecialchars($customer['phone']); ?></div>
                                            <?php if ($customer['email']): ?>
                                            <div class="text-muted" style="font-size: 0.75rem;"><?php echo htmlspecialchars($customer['email']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-badge customer-<?php echo strtolower($customer['customer_type']); ?>">
                                                <?php echo $customer['customer_type']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo strtolower($customer['status']); ?>">
                                                <?php echo ucfirst(strtolower($customer['status'])); ?>
                                            </span>
                                        </td>
                                        <td class="fw-bold"><?php echo number_format($customer['total_orders']); ?></td>
                                        <td class="fw-bold">KSh <?php echo number_format($customer['total_spent']); ?></td>
                                        <td class="fw-bold" style="color: #f59e0b;"><?php echo number_format($customer['loyalty_points']); ?></td>
                                        <td class="text-muted">
                                            <?php 
                                            if ($customer['last_order_date']) {
                                                echo date('M j, Y', strtotime($customer['last_order_date']));
                                            } else {
                                                echo 'No orders';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <div class="d-flex gap-2">
                                                <a href="view_customer.php?id=<?php echo $customer['customer_id']; ?>" 
                                                   class="btn-outline" title="View Details">
                                                    <i class="ph-eye"></i>
                                                </a>
                                                <a href="edit_customer.php?id=<?php echo $customer['customer_id']; ?>" 
                                                   class="btn-outline" title="Edit Customer">
                                                    <i class="ph-pencil"></i>
                                                </a>
                                                <a href="new_order.php?customer=<?php echo $customer['customer_id']; ?>" 
                                                   class="btn-primary" title="New Order">
                                                    <i class="ph-plus"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" style="text-align: center; padding: 3rem; color: #64748b;">
                                            <div style="font-size: 3rem; margin-bottom: 1rem;">👥</div>
                                            <div style="font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem;">No customers found</div>
                                            <div>Try adjusting your search criteria or add a new customer</div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="pagination">
                            <?php
                            // Build query string without page parameter
                            $query_params = $_GET;
                            unset($query_params['page']);
                            $query_string = http_build_query($query_params);
                            $query_string = $query_string ? '&' . $query_string : '';
                            ?>
                            
                            <?php if ($page > 1): ?>
                            <a href="?page=<?php echo $page - 1; ?><?php echo $query_string; ?>">← Previous</a>
                            <?php endif; ?>
                            
                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            if ($start_page > 1) {
                                echo '<a href="?page=1' . $query_string . '">1</a>';
                                if ($start_page > 2) {
                                    echo '<span>...</span>';
                                }
                            }
                            
                            for ($i = $start_page; $i <= $end_page; $i++) {
                                if ($i == $page) {
                                    echo '<span class="current">' . $i . '</span>';
                                } else {
                                    echo '<a href="?page=' . $i . $query_string . '">' . $i . '</a>';
                                }
                            }
                            
                            if ($end_page < $total_pages) {
                                if ($end_page < $total_pages - 1) {
                                    echo '<span>...</span>';
                                }
                                echo '<a href="?page=' . $total_pages . $query_string . '">' . $total_pages . '</a>';
                            }
                            ?>
                            
                            <?php if ($page < $total_pages): ?>
                            <a href="?page=<?php echo $page + 1; ?><?php echo $query_string; ?>">Next →</a>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        // Auto-submit form on filter change
        document.querySelectorAll('select[name="customer_type"], select[name="status"], select[name="sort"], select[name="order"]').forEach(function(select) {
            select.addEventListener('change', function() {
                this.form.submit();
            });
        });

        // Handle search input with debounce
        let searchTimeout;
        document.querySelector('input[name="search"]').addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const form = this.form;
            searchTimeout = setTimeout(function() {
                // Only submit if there's a search term or if clearing search
                form.submit();
            }, 500);
        });

        // Clear filters functionality
        function clearFilters() {
            window.location.href = 'list_customers.php';
        }

        // Add clear filters button if any filters are active
        const hasFilters = <?php echo json_encode(!empty($search) || !empty($customer_type_filter) || !empty($status_filter)); ?>;
        if (hasFilters) {
            const filtersCard = document.querySelector('.filters-card .row');
            const clearBtn = document.createElement('div');
            clearBtn.className = 'col-md-12 text-end mt-2';
            clearBtn.innerHTML = '<button type="button" onclick="clearFilters()" class="btn-secondary btn-sm">Clear Filters</button>';
            filtersCard.appendChild(clearBtn);
        }

        // Row click functionality
        document.querySelectorAll('.data-table tbody tr').forEach(function(row) {
            if (!row.querySelector('td[colspan]')) {
                row.style.cursor = 'pointer';
                row.addEventListener('click', function(e) {
                    // Don't trigger on action button clicks
                    if (!e.target.closest('.btn-outline, .btn-primary')) {
                        const viewLink = this.querySelector('a[href*="view_customer"]');
                        if (viewLink) {
                            window.location.href = viewLink.href;
                        }
                    }
                });
            }
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>