<?php
require_once 'config/db.php';

// Handle Bulk Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && !empty($_POST['selected_customers'])) {
    $ids = array_map('intval', $_POST['selected_customers']);
    $ids_string = implode(',', $ids);
    try {
        $pdo->query("DELETE FROM customers WHERE id IN ($ids_string)");
        $msg = "bulk_deleted";
        header("Location: customers.php?msg=$msg");
        exit;
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Handle Single Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM customers WHERE id = ?")->execute([$id]);
    header("Location: customers.php?msg=deleted");
    exit;
}

// Handle Status Toggle
if (isset($_GET['toggle']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $pdo->prepare("UPDATE customers SET status = CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id = ?")->execute([$id]);
    header("Location: customers.php?msg=updated");
    exit;
}

// Messages
$msg_map = ['deleted' => 'Customer deleted.', 'bulk_deleted' => 'Selected customers deleted.', 'updated' => 'Status updated.', 'converted' => 'Lead successfully converted to customer!'];
if (isset($_GET['msg'])) $success = $msg_map[$_GET['msg']] ?? '';

// Filters
$search = $_GET['search'] ?? '';
$f_status = $_GET['status'] ?? '';

$sql = "SELECT c.*, l.phone as lead_phone FROM customers c LEFT JOIN leads l ON c.lead_id = l.id WHERE 1=1";
$params = [];

if (!empty($search)) {
    $sql .= " AND (c.name LIKE ? OR c.phone LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%";
}
if (!empty($f_status)) {
    $sql .= " AND c.status = ?";
    $params[] = $f_status;
}
$sql .= " ORDER BY c.converted_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$customers = $stmt->fetchAll();

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:15px;">
        <div>
            <h2><i class="fa-solid fa-user-check"></i> Customers</h2>
            <p>All leads that have been converted to customers.</p>
        </div>
        <div style="background:rgba(255,255,255,0.15); padding:15px 20px; border-radius:10px; text-align:center;">
            <div style="font-size:1.8rem; font-weight:700;"><?= count($customers) ?></div>
            <div style="font-size:0.85rem; opacity:0.85;">Total Customers</div>
        </div>
    </div>

    <?php if (!empty($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom:20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div style="background:#fee2e2; color:#ef4444; padding:15px; border-radius:8px; margin-bottom:20px;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Filters -->
    <div class="data-card" style="background:#fff; padding:20px; border-radius:12px; margin-bottom:20px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
        <form method="GET" style="display:flex; gap:15px; flex-wrap:wrap; align-items:flex-end;">
            <div style="flex:2; min-width:200px;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Search</label>
                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Name or phone..." style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div style="flex:1; min-width:140px;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Status</label>
                <select name="status" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">All</option>
                    <option value="active" <?= $f_status === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= $f_status === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
            <div>
                <button type="submit" style="padding:10px 20px; background:var(--dark); color:#fff; border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
                <?php if (!empty($search) || !empty($f_status)): ?>
                    <a href="customers.php" style="margin-left:5px; padding:10px 15px; background:#e2e8f0; color:var(--dark); text-decoration:none; border-radius:6px; font-weight:600; display:inline-block;">Reset</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Table -->
    <style>
        .btn-3d { display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; border-radius:8px; text-decoration:none; transition:all 0.1s ease; position:relative; top:0; border:none; cursor:pointer; margin-left:6px; }
        .btn-3d-view { background:#3b82f6; color:#fff; box-shadow:0 4px 0 #2563eb, 0 5px 8px rgba(0,0,0,0.15); }
        .btn-3d-del { background:#ef4444; color:#fff; box-shadow:0 4px 0 #dc2626, 0 5px 8px rgba(0,0,0,0.15); }
        .btn-3d:active { top:4px; box-shadow:none; }
        .custom-checkbox { width:18px; height:18px; cursor:pointer; accent-color:var(--primary); }

        @media (max-width: 768px) {
            /* Force compact ROW view — override the global card transform */
            .admin-table, .admin-table thead, .admin-table tbody,
            .admin-table th, .admin-table td, .admin-table tr {
                display: revert !important;
            }
            .admin-table { width:100%; border-collapse:collapse; }
            .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
            .admin-table th, .admin-table td {
                padding: 10px 5px !important;
                font-size: 0.78rem !important;
                vertical-align: middle !important;
                min-height: auto !important;
                padding-left: 5px !important;
                border-bottom: 1px solid #f1f5f9 !important;
                border: none !important;
                border-bottom: 1px solid #f1f5f9 !important;
            }
            .admin-table tr {
                border: none !important;
                border-radius: 0 !important;
                margin-bottom: 0 !important;
                padding: 0 !important;
                box-shadow: none !important;
                display: table-row !important;
            }
            .admin-table td:before { display: none !important; content: none !important; }
            
            /* Hide non-essential columns on mobile */
            .admin-table th:nth-child(4), .admin-table td:nth-child(4), /* Address */
            .admin-table th:nth-child(5), .admin-table td:nth-child(5), /* Project Type */
            .admin-table th:nth-child(6), .admin-table td:nth-child(6), /* Converted On */
            .admin-table th:nth-child(7), .admin-table td:nth-child(7)  /* Status */
            { display: none !important; }

            .dashboard-content { padding: 10px !important; }
        }
    </style>

    <div class="recent-activity" style="padding:0;">
        <form action="customers.php" method="POST" id="bulkForm">
            <div style="padding:15px 20px; background:#f8fafc; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; border-radius:12px 12px 0 0;">
                <label style="display:flex; align-items:center; cursor:pointer; font-weight:600; color:var(--dark);">
                    <input type="checkbox" id="selectAll" class="custom-checkbox" style="margin-right:12px;"> Select All
                </label>
                <button type="submit" name="bulk_action" value="delete" class="btn-3d btn-3d-del" style="width:auto; padding:0 15px; font-size:0.85rem; height:34px; margin:0;" onclick="return confirm('Permanently delete selected customers?');">
                    <i class="fa-solid fa-trash" style="margin-right:6px;"></i> Bulk Delete
                </button>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="padding-left:20px; width:40px;"></th>
                            <th style="width:60px;">S.No</th>
                            <th>Contact Number</th>
                            <th>Address</th>
                            <th>Project Type</th>
                            <th>Converted On</th>
                            <th>Status</th>
                            <th style="text-align:right; padding-right:20px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($customers) > 0): ?>
                            <?php $sno = 1; foreach ($customers as $c): ?>
                            <tr>
                                <td style="padding-left:20px;"><input type="checkbox" name="selected_customers[]" value="<?= $c['id'] ?>" class="custom-checkbox cust-cb"></td>
                                <td style="color:#64748b; font-weight:500;">#<?= $sno++ ?></td>
                                <td style="font-weight:700; color:var(--dark); font-size:1.05rem;"><?= htmlspecialchars($c['phone']) ?></td>
                                <td style="color:#64748b; font-size:0.85rem;">
                                    <?php 
                                        $addr_parts = array_filter([$c['building_name'], $c['area'], $c['city'], $c['district'], $c['pincode'], $c['state']]);
                                        echo htmlspecialchars(implode(', ', $addr_parts) ?: '—');
                                    ?>
                                </td>
                                <td style="color:#64748b;"><?= htmlspecialchars($c['project_type'] ?? '—') ?></td>
                                <td style="color:#64748b; font-size:0.9rem;"><?= date('M d, Y', strtotime($c['converted_at'])) ?></td>
                                <td>
                                    <a href="customers.php?toggle=1&id=<?= $c['id'] ?>" style="text-decoration:none;">
                                        <?php if ($c['status'] === 'active'): ?>
                                            <span class="badge badge-completed"><i class="fa-solid fa-circle-check"></i> Active</span>
                                        <?php else: ?>
                                            <span class="badge" style="background:#f1f5f9; color:#64748b; border:1px solid #e2e8f0;"><i class="fa-regular fa-circle-xmark"></i> Inactive</span>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td style="text-align:right; padding-right:20px;">
                                    <?php if ($c['lead_id']): ?>
                                        <a href="lead_view.php?id=<?= $c['lead_id'] ?>" class="btn-3d btn-3d-view" title="View Original Lead"><i class="fa-solid fa-eye"></i></a>
                                    <?php endif; ?>
                                    <a href="customers.php?delete=<?= $c['id'] ?>" class="btn-3d btn-3d-del" title="Delete" onclick="return confirm('Delete this customer?');"><i class="fa-solid fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align:center; padding:50px 20px; color:#94a3b8;">
                                    <i class="fa-solid fa-user-slash" style="font-size:2.5rem; display:block; margin-bottom:10px; color:#cbd5e1;"></i>
                                    No customers yet. Convert a lead to get started!
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.cust-cb').forEach(cb => cb.checked = this.checked);
});
</script>

<?php require_once 'includes/footer.php'; ?>
