<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

$tenant_id = (int) $_SESSION['tenant_id'];
$db = DB::connect();

// Si el negocio no está configurado, al onboarding.
$stmt = $db->prepare("SELECT onboarding_status FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tenant_id]);
if ($stmt->fetchColumn() !== 'live') {
    header('Location: /onboarding');
    exit;
}

// Cambiar estado de un lead (scopeado por tenant).
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $leadId = (int) ($_POST['lead_id'] ?? 0);
    $newStatus = $_POST['status'] ?? '';
    $allowed = ['new', 'qualified', 'booked', 'won', 'lost'];
    if ($leadId > 0 && in_array($newStatus, $allowed, true)) {
        $stmt = $db->prepare("UPDATE leads SET status = :s WHERE id = :id AND tenant_id = :t");
        $stmt->execute([':s' => $newStatus, ':id' => $leadId, ':t' => $tenant_id]);
        $_SESSION['flash'] = 'Lead actualizado.';
    }
    header('Location: /leads');
    exit;
}

$flash = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);

// Leads del tenant + datos del contacto + perfil si existe.
$stmt = $db->prepare(
    "SELECT l.id, l.status, l.value_estimate, l.source, l.created_at,
            c.id AS contact_id, c.name AS contact_name, c.phone AS contact_phone, c.channel AS contact_channel,
            cp.email AS cp_email, cp.birthday AS cp_birthday,
            cp.notes AS cp_notes, cp.preferences AS cp_preferences
     FROM leads l
     JOIN contacts c ON l.contact_id = c.id AND c.tenant_id = l.tenant_id
     LEFT JOIN client_profiles cp ON cp.contact_id = c.id AND cp.tenant_id = l.tenant_id
     WHERE l.tenant_id = :t
     ORDER BY l.created_at DESC"
);
$stmt->execute([':t' => $tenant_id]);
$leads = $stmt->fetchAll();

// Conteos por estado (para el resumen).
$counts = ['new' => 0, 'qualified' => 0, 'booked' => 0, 'won' => 0, 'lost' => 0];
foreach ($leads as $l) {
    if (isset($counts[$l['status']])) {
        $counts[$l['status']]++;
    }
}

require dirname(__DIR__) . '/views/leads.php';
