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

// Handle merge action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['merge_action'])) {
    $master_id = (int)$_POST['master_id'];
    $merge_ids = array_map('intval', $_POST['merge_ids'] ?? []);
    
    if ($master_id > 0 && !empty($merge_ids)) {
        try {
            // Re-assign followups from duplicates to master
            foreach ($merge_ids as $dup_id) {
                if ($dup_id === $master_id) continue;
                $pdo->prepare("UPDATE lead_followups SET lead_id = ? WHERE lead_id = ?")->execute([$master_id, $dup_id]);
                // Append notes
                $dup_data = $pdo->query("SELECT notes FROM leads WHERE id = $dup_id")->fetch();
                if (!empty($dup_data['notes'])) {
                    $pdo->prepare("UPDATE leads SET notes = CONCAT(IFNULL(notes,''), '\n[Merged] ', ?) WHERE id = ?")->execute([$dup_data['notes'], $master_id]);
                }
                // Junk the duplicate
                $pdo->prepare("UPDATE leads SET is_junk = 1 WHERE id = ?")->execute([$dup_id]);
            }
            $success = "Leads merged successfully. Duplicates moved to junk.";
        } catch (PDOException $e) {
            $error = "Merge error: " . $e->getMessage();
        }
    }
}

// Handle single junk
if (isset($_GET['junk'])) {
    $junk_id = (int)$_GET['junk'];
    $pdo->prepare("UPDATE leads SET is_junk = 1 WHERE id = ?")->execute([$junk_id]);
    header("Location: lead_duplicates.php?msg=junked");
    exit;
}

if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'junked') $success = "Lead moved to junk.";
}

require_once 'includes/header.php';

// Find duplicate groups by phone
$dup_sql = "
    SELECT phone, COUNT(*) as cnt, GROUP_CONCAT(id ORDER BY created_at ASC) as lead_ids
    FROM leads
    WHERE is_junk = 0 AND phone != '' AND phone IS NOT NULL
    GROUP BY phone
    HAVING cnt > 1
    ORDER BY cnt DESC, phone ASC
";
$dup_groups = $pdo->query($dup_sql)->fetchAll();

// For each group, fetch full lead details
$grouped_leads = [];
foreach ($dup_groups as $group) {
    $ids = explode(',', $group['lead_ids']);
    $in = implode(',', $ids);
    $leads_in_group = $pdo->query("
        SELECT l.*, ls.name as status_name, ls.color_code as status_color
        FROM leads l
        LEFT JOIN lead_statuses ls ON l.status_id = ls.id
        WHERE l.id IN ($in)
        ORDER BY l.created_at ASC
    ")->fetchAll();
    $grouped_leads[$group['phone']] = $leads_in_group;
}
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px; display:flex; justify-content:space-between; align-items:center;">
        <div>
            <h2><i class="fa-solid fa-copy"></i> Duplicate Lead Finder</h2>
            <p>Find and merge/junk leads sharing the same contact number.</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($dup_groups) ?></div>
            <div style="font-size:0.85rem; opacity:0.85;">Duplicate Groups</div>
        </div>
    </div>

    <?php if (isset($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; ?>

    <?php if (empty($dup_groups)): ?>
        <div class="data-card" style="background:#fff; padding:50px; text-align:center; border-radius:12px;">
            <i class="fa-solid fa-circle-check" style="font-size:3rem; color:#22c55e; margin-bottom:15px; display:block;"></i>
            <h3 style="color:var(--dark); margin-bottom:8px;">No duplicates found!</h3>
            <p style="color:#64748b;">All your leads have unique contact numbers.</p>
        </div>
    <?php else: ?>

    <style>
        .dup-group { background:#fff; border-radius:12px; border:1px solid var(--border); margin-bottom:20px; overflow:hidden; }
        .dup-group-header { padding:15px 20px; background:#f8fafc; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; cursor:pointer; }
        .dup-group-body { padding:0; }
        .dup-lead-row { display:grid; grid-template-columns: auto 1fr auto auto; gap:15px; align-items:center; padding:15px 20px; border-bottom:1px solid #f1f5f9; }
        .dup-lead-row:last-child { border-bottom:none; }
        .badge-status { padding:4px 10px; border-radius:12px; font-size:0.8rem; font-weight:600; }
        .btn-sm { display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:6px; text-decoration:none; font-size:0.8rem; border:none; cursor:pointer; }
        .btn-sm-view { background:#e0f2fe; color:#0284c7; }
        .btn-sm-junk { background:#fef3c7; color:#d97706; }
    </style>

    <?php foreach ($grouped_leads as $phone => $leads): ?>
        <div class="dup-group">
            <div class="dup-group-header" onclick="this.nextElementSibling.classList.toggle('hidden')">
                <div style="display:flex; align-items:center; gap:15px;">
                    <div style="background:#fee2e2; width:40px; height:40px; border-radius:8px; display:flex; align-items:center; justify-content:center;">
                        <i class="fa-solid fa-phone" style="color:#ef4444;"></i>
                    </div>
                    <div>
                        <div style="font-weight:700; font-size:1.1rem; color:var(--dark);"><?= htmlspecialchars($phone) ?></div>
                        <div style="font-size:0.85rem; color:#64748b;"><?= count($leads) ?> leads with this number</div>
                    </div>
                </div>
                <div style="display:flex; align-items:center; gap:10px;">
                    <span style="background:#fee2e2; color:#ef4444; padding:4px 12px; border-radius:20px; font-size:0.8rem; font-weight:700;"><?= count($leads) ?> duplicates</span>
                    <i class="fa-solid fa-chevron-down" style="color:#64748b;"></i>
                </div>
            </div>

            <div class="dup-group-body">
                <form action="lead_duplicates.php" method="POST" onsubmit="return confirmMerge(this)">
                    <!-- Merge bar -->
                    <div style="padding:12px 20px; background:#fffbeb; border-bottom:1px solid #fde68a; display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
                        <i class="fa-solid fa-code-merge" style="color:#d97706;"></i>
                        <span style="font-weight:600; font-size:0.9rem; color:#92400e;">Select master lead below, check duplicates to merge into it:</span>
                        <button type="submit" name="merge_action" value="1" style="margin-left:auto; padding:6px 15px; background:#f59e0b; color:#fff; border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-code-merge"></i> Merge Checked into Master</button>
                    </div>

                    <?php foreach ($leads as $idx => $lead): ?>
                    <div class="dup-lead-row">
                        <div>
                            <?php if ($idx === 0): ?>
                                <!-- First lead is default master -->
                                <input type="hidden" name="master_id" value="<?= $lead['id'] ?>">
                                <div style="background:#d1fae5; color:#059669; padding:4px 8px; border-radius:6px; font-size:0.75rem; font-weight:600; text-align:center;">MASTER</div>
                            <?php else: ?>
                                <input type="checkbox" name="merge_ids[]" value="<?= $lead['id'] ?>" class="custom-checkbox" style="width:18px; height:18px; accent-color:#f59e0b;">
                            <?php endif; ?>
                        </div>
                        <div>
                            <div style="font-weight:700; color:var(--dark);"><?= htmlspecialchars($lead['name'] ?? 'Unknown') ?></div>
                            <div style="font-size:0.82rem; color:#64748b; margin-top:2px;">
                                Added: <?= date('M d, Y', strtotime($lead['created_at'])) ?>
                            </div>
                        </div>
                        <div>
                            <?php if ($lead['status_name']): ?>
                                <span class="badge-status" style="background:<?= $lead['status_color'] ?>22; color:<?= $lead['status_color'] ?>; border:1px solid <?= $lead['status_color'] ?>44;"><?= htmlspecialchars($lead['status_name']) ?></span>
                            <?php else: ?>
                                <span style="color:#94a3b8; font-size:0.8rem;">No Status</span>
                            <?php endif; ?>
                        </div>
                        <div style="display:flex; gap:6px;">
                            <a href="lead_view.php?id=<?= $lead['id'] ?>" class="btn-sm btn-sm-view" title="View Lead"><i class="fa-solid fa-eye"></i></a>
                            <?php if ($idx > 0): ?>
                                <a href="lead_duplicates.php?junk=<?= $lead['id'] ?>" class="btn-sm btn-sm-junk" title="Move to Junk" onclick="return confirm('Move this lead to junk?');"><i class="fa-solid fa-ban"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </form>
            </div>
        </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<script>
function confirmMerge(form) {
    const checked = form.querySelectorAll('input[name="merge_ids[]"]:checked');
    if (checked.length === 0) {
        alert('Please check at least one duplicate to merge into the master lead.');
        return false;
    }
    return confirm('Merge selected leads into the MASTER lead? Duplicates will be moved to junk. This cannot be undone.');
}
</script>

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