<?php
require_once 'includes/header.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 {
        // Security: only delete customers assigned to this agent
        $pdo->query("DELETE FROM customers WHERE id IN ($ids_string) AND agent_id = $agent_id");
        header("Location: customers.php?msg=bulk_deleted");
        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 = ? AND agent_id = ?")->execute([$id, $agent_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 = ? AND agent_id = ?")->execute([$id, $agent_id]);
    header("Location: customers.php?msg=updated");
    exit;
}

// 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 c.agent_id = ?";
$params = [$agent_id];

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();
?>

<script>document.getElementById('page-title').textContent='My Customers';</script>

<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;background:linear-gradient(135deg, #0f172a, #334155);color:#fff;border:none;">
    <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
        <div>
            <h2 style="font-size:1.4rem;font-weight:800;margin-bottom:4px;"><i class="fa-solid fa-briefcase"></i> My Customers</h2>
            <p style="font-size:0.85rem;opacity:0.9;">Manage your successfully converted customers.</p>
        </div>
        <div style="background:rgba(255,255,255,0.1);padding:10px 18px;border-radius:10px;text-align:center;border:1px solid rgba(255,255,255,0.1);">
            <div style="font-size:1.4rem;font-weight:800;line-height:1;"><?=count($customers)?></div>
            <div style="font-size:0.75rem;opacity:0.8;margin-top:4px;">Total Customers</div>
        </div>
    </div>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert-success">Action completed successfully.</div>
<?php endif; ?>

<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;">
    <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
        <div style="flex:2;min-width:200px;">
            <label>Search</label>
            <input type="text" name="search" value="<?=htmlspecialchars($search)?>" placeholder="Name or phone...">
        </div>
        <div style="flex:1;min-width:130px;">
            <label>Status</label>
            <select name="status">
                <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 style="display:flex;gap:8px;">
            <button type="submit" class="btn-primary"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
            <?php if(!empty($search)||!empty($f_status)): ?><a href="customers.php" class="btn-primary" style="background:#f1f5f9;color:#64748b;"><i class="fa-solid fa-xmark"></i> Clear</a><?php endif; ?>
        </div>
    </form>
</div>

<div class="ag-card" style="padding:0;overflow:hidden;">
    <form action="customers.php" method="POST">
        <div style="padding:16px 22px;border-bottom:2px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
            <label style="display:flex;align-items:center;cursor:pointer;font-weight:700;font-size:0.9rem;gap:10px;">
                <input type="checkbox" id="selectAll" style="width:17px;height:17px;accent-color:var(--primary);">
                Select All Customers
            </label>
            <button type="submit" name="bulk_action" value="delete" class="btn-primary" style="background:#fee2e2;color:#ef4444;border:none;padding:7px 14px;font-size:0.8rem;" onclick="return confirm('Delete selected customers?')">
                <i class="fa-solid fa-trash"></i> Bulk Delete
            </button>
        </div>

        <div style="overflow-x:auto;">
            <table class="ag-table">
                <thead>
                    <tr>
                        <th style="width:40px;"></th>
                        <th>Customer Name</th>
                        <th>Contact info</th>
                        <th>Address</th>
                        <th>Project Type</th>
                        <th>Converted On</th>
                        <th>Status</th>
                        <th style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($customers)): ?>
                    <tr><td colspan="7" style="text-align:center;padding:40px;color:#94a3b8;"><i class="fa-solid fa-user-slash" style="font-size:2rem;display:block;margin-bottom:10px;color:#e2e8f0;"></i>No customers found.</td></tr>
                <?php else: foreach ($customers as $c): ?>
                    <tr>
                        <td><input type="checkbox" name="selected_customers[]" value="<?=$c['id']?>" class="cust-cb"></td>
                        <td><div style="font-weight:700;color:#1e293b;"><?=htmlspecialchars($c['name'])?></div></td>
                        <td>
                            <div style="font-weight:600;color:var(--primary);"><?=htmlspecialchars($c['phone'])?></div>
                            <?php if($c['email']): ?><div style="font-size:0.75rem;color:#94a3b8;"><?=htmlspecialchars($c['email'])?></div><?php endif; ?>
                        </td>
                        <td>
                            <div style="font-size:0.82rem; color:#64748b; line-height:1.4;">
                                <?php 
                                    $addr_parts = array_filter([$c['building_name'], $c['area'], $c['city'], $c['district'], $c['pincode'], $c['state']]);
                                    echo htmlspecialchars(implode(', ', $addr_parts) ?: '—');
                                ?>
                            </div>
                        </td>
                        <td><div style="font-size:0.85rem;color:#64748b;"><?=htmlspecialchars($c['project_type'] ?: '—')?></div></td>
                        <td><div style="font-size:0.85rem;color:#64748b;"><?=date('d M, Y', strtotime($c['converted_at']))?></div></td>
                        <td>
                            <a href="customers.php?toggle=1&id=<?=$c['id']?>" style="text-decoration:none;">
                                <span style="display:inline-block;padding:3px 10px;border-radius:10px;font-size:0.7rem;font-weight:700;background:<?=($c['status']==='active')?'#dcfce7':'#f1f5f9'?>;color:<?=($c['status']==='active')?'#16a34a':'#64748b'?>;border:1px solid <?=($c['status']==='active')?'#bbf7d0':'#e2e8f0'?>;">
                                    <?=ucfirst($c['status'])?>
                                </span>
                            </a>
                        </td>
                        <td style="text-align:right;">
                            <?php if($c['lead_id']): ?>
                                <a href="lead_view.php?id=<?=$c['lead_id']?>" style="color:#3b82f6;background:#e0f2fe;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:6px;text-decoration:none;" title="View Lead"><i class="fa-solid fa-eye"></i></a>
                            <?php endif; ?>
                            <a href="customers.php?delete=<?=$c['id']?>" style="color:#ef4444;background:#fee2e2;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:6px;text-decoration:none;" title="Delete" onclick="return confirm('Delete this customer?')"><i class="fa-solid fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </form>
</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'; ?>
