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

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

// Get user details
$user_id = $_SESSION['user_id'];
$role_name = $_SESSION['role_name'];

// Pagination settings
$records_per_page = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$segment_filter = isset($_GET['segment']) ? (int)$_GET['segment'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$kyc_filter = isset($_GET['kyc']) ? $_GET['kyc'] : '';

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

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

if (!empty($segment_filter)) {
    $where_conditions[] = "c.segment_id = ?";
    $params[] = $segment_filter;
    $param_types .= 'i';
}

if (!empty($status_filter)) {
    $where_conditions[] = "c.is_active = ?";
    $params[] = ($status_filter == 'active') ? 1 : 0;
    $param_types .= 'i';
}

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

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

// Get total count for pagination
$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_records = $count_stmt->get_result()->fetch_assoc()['total'];
    $count_stmt->close();
} else {
    $total_records = $conn->query($count_sql)->fetch_assoc()['total'];
}

$total_pages = ceil($total_records / $records_per_page);

// Get customers with segment information
$sql = "SELECT 
    c.*,
    cs.segment_name,
    (SELECT COUNT(*) FROM policies p WHERE p.customer_id = c.customer_id AND p.status = 'ACTIVE') as active_policies,
    (SELECT SUM(pp.total_amount) FROM premium_payments pp 
     JOIN policies p ON pp.policy_id = p.policy_id 
     WHERE p.customer_id = c.customer_id AND pp.status = 'COMPLETED') as total_premiums,
    (SELECT COUNT(*) FROM claims cl 
     JOIN policies p ON cl.policy_id = p.policy_id 
     WHERE p.customer_id = c.customer_id) as total_claims
FROM customers c
LEFT JOIN customer_segments cs ON c.segment_id = cs.segment_id
$where_clause
ORDER BY c.created_at DESC
LIMIT ? OFFSET ?";

// Add pagination parameters
$params[] = $records_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 customer segments for filter dropdown
$segments_sql = "SELECT segment_id, segment_name FROM customer_segments ORDER BY segment_name";
$segments_result = $conn->query($segments_sql);

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_customers,
    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_customers,
    SUM(CASE WHEN kyc_status = 'VERIFIED' THEN 1 ELSE 0 END) as verified_customers,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
FROM customers";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Directory - Ultrasure Insurance')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <style>
        .customer-avatar {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .stats-card {
            border: none;
            border-radius: 15px;
            transition: all 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .customer-status {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
        }
        
        .search-filters {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .table-enhanced {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .table-enhanced thead th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
            border: none;
        }
        
        .table-enhanced tbody tr {
            transition: all 0.3s ease;
        }
        
        .table-enhanced tbody tr:hover {
            background-color: #f8f9fa;
            transform: scale(1.01);
        }
        
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
            margin-right: 0.25rem;
        }
        
        .pagination-wrapper {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
    </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="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Customer Directory</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Customer Management</li>
                                        <li class="breadcrumb-item active">Customer Directory</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                <i class="ri-user-3-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Total Customers</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_customers']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success text-success rounded-circle fs-3">
                                                <i class="ri-user-check-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Active Customers</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['active_customers']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info text-info rounded-circle fs-3">
                                                <i class="ri-shield-check-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">KYC Verified</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['verified_customers']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning text-warning rounded-circle fs-3">
                                                <i class="ri-user-add-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">New Today</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['new_today']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filters -->
                    <div class="search-filters">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Search Customers</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="ri-search-line"></i></span>
                                    <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Name, email, phone, ID...">
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Segment</label>
                                <select class="form-select" name="segment">
                                    <option value="">All Segments</option>
                                    <?php 
                                    $segments_result->data_seek(0);
                                    while($segment = $segments_result->fetch_assoc()): ?>
                                        <option value="<?php echo $segment['segment_id']; ?>" 
                                                <?php echo $segment_filter == $segment['segment_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($segment['segment_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" 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>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">KYC Status</label>
                                <select class="form-select" name="kyc">
                                    <option value="">All KYC</option>
                                    <option value="PENDING" <?php echo $kyc_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="VERIFIED" <?php echo $kyc_filter == 'VERIFIED' ? 'selected' : ''; ?>>Verified</option>
                                    <option value="REJECTED" <?php echo $kyc_filter == 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ri-search-line me-1"></i> Filter
                                    </button>
                                    <a href="list_customers.php" class="btn btn-soft-secondary">
                                        <i class="ri-refresh-line"></i>
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Customer Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h4 class="card-title mb-0">Customer List</h4>
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-soft-success" onclick="exportCustomers()">
                                                <i class="ri-file-excel-line me-1"></i> Export
                                            </button>
                                            <a href="add_customer.php" class="btn btn-primary">
                                                <i class="ri-user-add-line me-1"></i> Add Customer
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-enhanced table-hover mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Customer</th>
                                                    <th>Contact Info</th>
                                                    <th>Segment</th>
                                                    <th>KYC Status</th>
                                                    <th>Policies</th>
                                                    <th>Total Premiums</th>
                                                    <th>Claims</th>
                                                    <th>Status</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 bg-soft-primary text-primary me-3">
                                                                        <?php echo strtoupper(substr($customer['first_name'], 0, 1) . substr($customer['last_name'], 0, 1)); ?>
                                                                    </div>
                                                                    <div>
                                                                        <h6 class="mb-1">
                                                                            <a href="view_customer.php?id=<?php echo $customer['customer_id']; ?>" class="text-dark text-decoration-none">
                                                                                <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                                                            </a>
                                                                        </h6>
                                                                        <p class="text-muted mb-0 small"><?php echo htmlspecialchars($customer['customer_number']); ?></p>
                                                                        <?php if($customer['national_id']): ?>
                                                                            <p class="text-muted mb-0 small">ID: <?php echo htmlspecialchars($customer['national_id']); ?></p>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            
                                                            <td>
                                                                <div>
                                                                    <?php if($customer['email']): ?>
                                                                        <p class="mb-1 small">
                                                                            <i class="ri-mail-line me-1"></i>
                                                                            <?php echo htmlspecialchars($customer['email']); ?>
                                                                        </p>
                                                                    <?php endif; ?>
                                                                    <p class="mb-0 small">
                                                                        <i class="ri-phone-line me-1"></i>
                                                                        <?php echo htmlspecialchars($customer['phone_primary']); ?>
                                                                    </p>
                                                                </div>
                                                            </td>
                                                            
                                                            <td>
                                                                <?php if($customer['segment_name']): ?>
                                                                    <span class="badge bg-soft-info text-info">
                                                                        <?php echo htmlspecialchars($customer['segment_name']); ?>
                                                                    </span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            
                                                            <td>
                                                                <?php
                                                                $kyc_class = match($customer['kyc_status']) {
                                                                    'VERIFIED' => 'success',
                                                                    'PENDING' => 'warning',
                                                                    'REJECTED' => 'danger',
                                                                    default => 'secondary'
                                                                };
                                                                ?>
                                                                <span class="badge bg-<?php echo $kyc_class; ?> customer-status">
                                                                    <?php echo ucfirst(strtolower($customer['kyc_status'])); ?>
                                                                </span>
                                                            </td>
                                                            
                                                            <td>
                                                                <span class="fw-semibold text-primary">
                                                                    <?php echo number_format($customer['active_policies']); ?>
                                                                </span>
                                                            </td>
                                                            
                                                            <td>
                                                                <span class="fw-semibold text-success">
                                                                    KSH <?php echo number_format($customer['total_premiums'] ?? 0, 2); ?>
                                                                </span>
                                                            </td>
                                                            
                                                            <td>
                                                                <span class="fw-semibold">
                                                                    <?php echo number_format($customer['total_claims']); ?>
                                                                </span>
                                                            </td>
                                                            
                                                            <td>
                                                                <?php if($customer['is_active']): ?>
                                                                    <span class="badge bg-success customer-status">Active</span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-danger customer-status">Inactive</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            
                                                            <td>
                                                                <div class="action-buttons">
                                                                    <a href="view_customer.php?id=<?php echo $customer['customer_id']; ?>" 
                                                                       class="btn btn-soft-primary" title="View Customer">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                    <a href="edit_customer.php?id=<?php echo $customer['customer_id']; ?>" 
                                                                       class="btn btn-soft-success" title="Edit Customer">
                                                                        <i class="ri-edit-line"></i>
                                                                    </a>
                                                                    <button class="btn btn-soft-info" 
                                                                            onclick="generateQuote(<?php echo $customer['customer_id']; ?>)" 
                                                                            title="Generate Quote">
                                                                        <i class="ri-file-add-line"></i>
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center py-4">
                                                            <div class="d-flex flex-column align-items-center">
                                                                <i class="ri-user-3-line fs-1 text-muted mb-3"></i>
                                                                <h5 class="text-muted">No customers found</h5>
                                                                <p class="text-muted">Try adjusting your search criteria or add a new customer.</p>
                                                                <a href="add_customer.php" class="btn btn-primary">
                                                                    <i class="ri-user-add-line me-1"></i> Add First Customer
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if($total_pages > 1): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="pagination-wrapper">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <p class="text-muted mb-0">
                                                Showing <?php echo $offset + 1; ?> to 
                                                <?php echo min($offset + $records_per_page, $total_records); ?> 
                                                of <?php echo $total_records; ?> entries
                                            </p>
                                        </div>
                                        
                                        <nav aria-label="Customer pagination">
                                            <ul class="pagination mb-0">
                                                <?php if($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&segment=<?php echo $segment_filter; ?>&status=<?php echo $status_filter; ?>&kyc=<?php echo $kyc_filter; ?>">
                                                            <i class="ri-arrow-left-line"></i>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                
                                                <?php for($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&segment=<?php echo $segment_filter; ?>&status=<?php echo $status_filter; ?>&kyc=<?php echo $kyc_filter; ?>">
                                                            <?php echo $i; ?>
                                                        </a>
                                                    </li>
                                                <?php endfor; ?>
                                                
                                                <?php if($page < $total_pages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&segment=<?php echo $segment_filter; ?>&status=<?php echo $status_filter; ?>&kyc=<?php echo $kyc_filter; ?>">
                                                            <i class="ri-arrow-right-line"></i>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function generateQuote(customerId) {
            window.location.href = 'quotes/new_quote.php?customer_id=' + customerId;
        }
        
        function exportCustomers() {
            // Get current filter parameters
            const params = new URLSearchParams(window.location.search);
            params.set('export', 'excel');
            
            // Create temporary form for export
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'export_customers.php';
            
            for (const [key, value] of params) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = value;
                form.appendChild(input);
            }
            
            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
        
        // Auto-submit form on filter change
        document.querySelectorAll('select[name="segment"], select[name="status"], select[name="kyc"]').forEach(function(select) {
            select.addEventListener('change', function() {
                this.form.submit();
            });
        });
    </script>
</body>
</html>

<?php
$stmt->close();
$conn->close();
?>