<?php
require_once 'auth.php';
ensureAdminAuth();

require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_customer'])) {
    try {
        $id = (int)$_POST['customer_id'];
        $isActive = (int)$_POST['is_active'];

        $stmt = $db->prepare("UPDATE customers SET is_active = :active WHERE id = :id");
        $stmt->execute([
            ':active' => $isActive,
            ':id' => $id
        ]);

        $message = 'Customer status updated.';
    } catch (Exception $e) {
        $error = 'Update failed: ' . $e->getMessage();
    }
}

/*
    FIXED SEARCH:
    Do not reuse the same :q placeholder multiple times.
    Some PDO/MySQL setups throw SQLSTATE[HY093] when the same named parameter is reused.
*/
$search = trim($_GET['search'] ?? '');
$where = '';
$params = [];

if ($search !== '') {
    $where = "
        WHERE 
            c.first_name LIKE :q_first_name
            OR c.last_name LIKE :q_last_name
            OR c.email LIKE :q_email
            OR c.phone_number LIKE :q_phone
    ";

    $searchTerm = "%{$search}%";

    $params[':q_first_name'] = $searchTerm;
    $params[':q_last_name'] = $searchTerm;
    $params[':q_email'] = $searchTerm;
    $params[':q_phone'] = $searchTerm;
}

try {
    $stmt = $db->prepare("
        SELECT 
            c.id, 
            c.first_name, 
            c.last_name, 
            c.email, 
            c.phone_number, 
            c.address, 
            c.zip_code, 
            c.is_active, 
            c.created_at, 
            city.city_name,
            (
                SELECT COUNT(*) 
                FROM service_requests sr 
                WHERE sr.customer_id = c.id
            ) AS request_count
        FROM customers c
        LEFT JOIN cities city ON c.city_id = city.id
        $where
        ORDER BY c.created_at DESC, c.id DESC
        LIMIT 200
    ");

    $stmt->execute($params);
    $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $customers = [];
    $error = 'Could not load customers: ' . $e->getMessage();
}

$total_customers = count($customers);
$active_customers = count(array_filter($customers, function($c) {
    return !isset($c['is_active']) || (int)$c['is_active'] === 1;
}));
$inactive_customers = $total_customers - $active_customers;
$total_requests = array_sum(array_map(function($c) {
    return (int)$c['request_count'];
}, $customers));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers - Admin</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --admin-bg-1: #080240;
            --admin-bg-2: #093349;
            --admin-card-1: #17295e;
            --admin-card-2: #102448;
            --admin-border: rgba(96, 165, 250, 0.24);
            --admin-border-strong: rgba(56, 189, 248, 0.42);
            --admin-cyan: #17bdd4;
            --admin-blue: #1d9bf0;
            --admin-text: #f8fafc;
            --admin-muted: #aebbd4;
            --admin-soft: #d7e7ff;
            --admin-green: #22c55e;
            --admin-yellow: #facc15;
            --admin-red: #f43f5e;
            --admin-input: rgba(8, 20, 48, 0.72);
        }

        * {
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, var(--admin-bg-1) 0%, var(--admin-bg-2) 100%) fixed !important;
            color: var(--admin-text) !important;
            font-family: 'Montserrat', sans-serif !important;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .sidebar {
            min-height: 100vh;
            background: rgba(8, 2, 64, 0.96);
            backdrop-filter: blur(14px);
            color: white;
            position: fixed;
            width: 250px;
            transition: all 0.3s;
            overflow-y: auto;
            z-index: 1000;
            border-right: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header {
            padding: 24px 18px;
            text-align: center;
            border-bottom: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header i {
            color: #ffffff;
        }

        .sidebar-header h4 {
            font-size: 1.1rem;
            margin-top: 10px;
            font-weight: 900;
            color: #ffffff;
        }

        .sidebar-header p {
            font-size: 0.8rem;
            color: var(--admin-muted);
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .sidebar-menu a {
            color: #b9dcff !important;
            padding: 13px 20px;
            display: block;
            text-decoration: none;
            transition: all 0.25s;
            border-left: 4px solid transparent;
            font-weight: 700;
            font-size: 14px;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(56, 189, 248, 0.12);
            color: #ffffff !important;
            border-left-color: var(--admin-cyan);
        }

        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
        }

        .main-content {
            margin-left: 250px;
            padding: 24px;
            min-height: 100vh;
            background: transparent !important;
        }

        .content-header {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            padding: 20px;
            border-radius: 18px;
            border: 1px solid rgba(56, 189, 248, 0.28);
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24);
            margin-bottom: 20px;
            color: #ffffff !important;
        }

        .content-header h2 {
            color: #ffffff !important;
            font-weight: 900;
        }

        .content-header h2 i {
            color: var(--admin-cyan) !important;
        }

        .content-header p,
        .text-muted {
            color: var(--admin-muted) !important;
        }

        .card {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            border: 1px solid rgba(56, 189, 248, 0.24) !important;
            border-radius: 16px !important;
            box-shadow:
                0 10px 24px rgba(0, 0, 0, 0.24),
                inset 0 0 0 1px rgba(255, 255, 255, 0.025) !important;
            color: #ffffff !important;
            overflow: hidden;
            transition: all 0.25s ease;
        }

        .card:hover {
            border-color: rgba(56, 189, 248, 0.38) !important;
        }

        .card-header {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
            padding: 15px 20px;
            font-weight: 900;
            color: #ffffff !important;
        }

        .card-header h5,
        .card-header h6,
        .card-header strong {
            color: #ffffff !important;
            font-weight: 900;
        }

        .card-body {
            padding: 20px;
            color: #ffffff !important;
        }

        h1, h2, h3, h4, h5, h6, strong, label {
            color: #ffffff !important;
        }

        .stat-card {
            height: 100%;
        }

        .stat-card:hover {
            transform: translateY(-3px);
        }

        .stat-icon-box {
            background: rgba(56, 189, 248, 0.14) !important;
            border: 1px solid rgba(56, 189, 248, 0.22);
            border-radius: 12px;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .stat-icon-box i {
            color: #dff7ff !important;
            font-size: 20px;
        }

        .form-control,
        .form-select,
        textarea,
        input {
            background-color: var(--admin-input) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
            min-height: 42px;
        }

        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #aebbd4 !important;
            opacity: 1;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: rgba(56, 189, 248, 0.62) !important;
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
        }

        .btn {
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .btn-primary,
        .btn-info {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            border: none !important;
            color: #ffffff !important;
        }

        .btn-secondary {
            background: rgba(148, 163, 184, 0.22) !important;
            border: 1px solid rgba(148, 163, 184, 0.30) !important;
            color: #ffffff !important;
        }

        .btn-outline-danger {
            border-color: rgba(244, 63, 94, 0.42) !important;
            color: #fecaca !important;
            background: rgba(244, 63, 94, 0.10) !important;
        }

        .btn-outline-danger:hover {
            background: rgba(244, 63, 94, 0.24) !important;
            color: #ffffff !important;
        }

        .btn-outline-success {
            border-color: rgba(34, 197, 94, 0.42) !important;
            color: #bbf7d0 !important;
            background: rgba(34, 197, 94, 0.10) !important;
        }

        .btn-outline-success:hover {
            background: rgba(34, 197, 94, 0.24) !important;
            color: #ffffff !important;
        }

        .badge {
            padding: 6px 10px;
            border-radius: 999px;
            font-weight: 900;
        }

        .badge.bg-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            color: #ffffff !important;
        }

        .badge.bg-info {
            background: rgba(56, 189, 248, 0.18) !important;
            color: #dff7ff !important;
            border: 1px solid rgba(56, 189, 248, 0.34);
        }

        .badge.bg-success {
            background: rgba(34, 197, 94, 0.18) !important;
            color: #bbf7d0 !important;
            border: 1px solid rgba(34, 197, 94, 0.34);
        }

        .badge.bg-secondary {
            background: rgba(148, 163, 184, 0.20) !important;
            border: 1px solid rgba(148, 163, 184, 0.34);
            color: #e2e8f0 !important;
        }

        .alert {
            border-radius: 14px;
            border: 1px solid rgba(56, 189, 248, 0.28) !important;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.14) !important;
            color: #bbf7d0 !important;
        }

        .alert-danger {
            background: rgba(244, 63, 94, 0.14) !important;
            color: #fecaca !important;
        }

        .table-responsive {
            border-radius: 12px;
            overflow-x: auto;
            background: transparent !important;
        }

        .table {
            color: var(--admin-text) !important;
            margin-bottom: 0 !important;
        }

        .table th {
            font-weight: 900;
            color: #ffffff !important;
            white-space: nowrap;
            background: rgba(8, 20, 48, 0.58) !important;
            border-color: rgba(96, 165, 250, 0.22) !important;
            font-size: 13px;
        }

        .table td {
            vertical-align: middle;
            color: var(--admin-soft) !important;
            border-color: rgba(96, 165, 250, 0.20) !important;
            background: rgba(8, 20, 48, 0.18) !important;
        }

        .table tbody tr:hover td {
            background: rgba(56, 189, 248, 0.10) !important;
            color: #ffffff !important;
        }

        .table small {
            color: var(--admin-muted) !important;
        }

        .table strong {
            color: #ffffff !important;
        }

        .customer-avatar {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            color: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 900;
            flex-shrink: 0;
            border: 1px solid rgba(255,255,255,0.18);
        }

        .customer-name-wrap {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }

            .main-content {
                margin-left: 0;
                padding: 14px;
            }

            .content-header {
                padding: 15px;
                display: block !important;
            }

            .content-header > div:last-child {
                margin-top: 12px;
            }

            .content-header h2 {
                font-size: 1.3rem;
            }

            .card-body {
                padding: 15px;
            }

            .table {
                min-width: 820px;
            }
        }
    </style>

    <link rel="stylesheet" href="../assets/theme.css">
    <link rel="stylesheet" href="../assets/portal-dark.css">
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/admin-sidebar.css">
</head>

<body>
    <?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar(); ?>

    <main class="main-content">
        <div class="content-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="mb-1">
                    <i class="fas fa-users me-2"></i>
                    Customer Management
                </h2>

                <p class="text-muted mb-0">
                    View, search, activate, and deactivate customer accounts.
                </p>
            </div>

            <div>
                <span class="badge bg-primary p-2">
                    <i class="fas fa-calendar me-1"></i>
                    <?php echo date('F d, Y'); ?>
                </span>
            </div>
        </div>

        <?php if($message): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="row mb-4">
            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Total Customers</h6>
                                <h3 class="mb-0"><?= number_format($total_customers) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-users"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Active</h6>
                                <h3 class="mb-0"><?= number_format($active_customers) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-user-check"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Inactive</h6>
                                <h3 class="mb-0"><?= number_format($inactive_customers) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-user-slash"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Total Requests</h6>
                                <h3 class="mb-0"><?= number_format($total_requests) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-clipboard-list"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-search me-2" style="color: var(--admin-cyan);"></i>
                Search Customers
            </div>

            <div class="card-body">
                <form class="row g-2" method="GET">
                    <div class="col-md-10">
                        <input 
                            type="text" 
                            name="search" 
                            class="form-control" 
                            placeholder="Search name, email, or phone"
                            value="<?= htmlspecialchars($search) ?>"
                        >
                    </div>

                    <div class="col-md-2">
                        <button class="btn btn-primary w-100">
                            <i class="fas fa-search me-1"></i> Search
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="fas fa-list me-2" style="color: var(--admin-cyan);"></i>
                    Customer Accounts
                </span>

                <span class="badge bg-info">
                    <?= number_format($total_customers) ?> records
                </span>
            </div>

            <div class="card-body table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Contact</th>
                            <th>City / ZIP</th>
                            <th>Requests</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach($customers as $c): ?>
                            <?php
                                $fullName = trim(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? ''));
                                $initials = strtoupper(substr($c['first_name'] ?? 'C', 0, 1) . substr($c['last_name'] ?? '', 0, 1));
                                if ($initials === '') {
                                    $initials = 'C';
                                }
                            ?>

                            <tr>
                                <td>
                                    <div class="customer-name-wrap">
                                        <div class="customer-avatar">
                                            <?= htmlspecialchars($initials) ?>
                                        </div>

                                        <div>
                                            <strong><?= htmlspecialchars($fullName ?: 'Customer') ?></strong><br>
                                            <small>ID #<?= (int)$c['id'] ?></small>
                                        </div>
                                    </div>
                                </td>

                                <td>
                                    <i class="fas fa-envelope me-1" style="color: var(--admin-cyan);"></i>
                                    <?= htmlspecialchars($c['email'] ?? '') ?><br>

                                    <small>
                                        <i class="fas fa-phone me-1" style="color: var(--admin-cyan);"></i>
                                        <?= htmlspecialchars($c['phone_number'] ?? '') ?>
                                    </small>
                                </td>

                                <td>
                                    <i class="fas fa-city me-1" style="color: var(--admin-cyan);"></i>
                                    <?= htmlspecialchars($c['city_name'] ?? 'N/A') ?><br>

                                    <small>
                                        <i class="fas fa-map-pin me-1" style="color: var(--admin-cyan);"></i>
                                        <?= htmlspecialchars($c['zip_code'] ?? '') ?>
                                    </small>
                                </td>

                                <td>
                                    <span class="badge bg-info">
                                        <?= (int)$c['request_count'] ?>
                                    </span>
                                </td>

                                <td>
                                    <?= !isset($c['is_active']) || $c['is_active'] 
                                        ? '<span class="badge bg-success">Active</span>' 
                                        : '<span class="badge bg-secondary">Inactive</span>' 
                                    ?>
                                </td>

                                <td>
                                    <form method="POST" class="mb-0">
                                        <input type="hidden" name="customer_id" value="<?= (int)$c['id'] ?>">
                                        <input type="hidden" name="is_active" value="<?= (!isset($c['is_active']) || $c['is_active']) ? 0 : 1 ?>">

                                        <button 
                                            name="toggle_customer" 
                                            class="btn btn-sm <?= (!isset($c['is_active']) || $c['is_active']) ? 'btn-outline-danger' : 'btn-outline-success' ?>"
                                        >
                                            <?= (!isset($c['is_active']) || $c['is_active']) ? 'Deactivate' : 'Activate' ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if(empty($customers)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="fas fa-users-slash fa-2x mb-2"></i><br>
                                    No customers found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>