<?php
// Crear 5 leads de muestra
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__); }

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

$db = getDB();
$pdo = $db->getConnection();

$now = date('Y-m-d H:i:s');
$leads = [
  ['first_name'=>'Mario','last_name'=>'Gómez','email'=>'mario.gomez@example.com','phone'=>'+34 600 111 001','company'=>'TechNova','job_title'=>'Analista','source'=>'website','status'=>'new','priority'=>'medium'],
  ['first_name'=>'Lucía','last_name'=>'Fernández','email'=>'lucia.fernandez@example.com','phone'=>'+34 600 111 002','company'=>'FinPlus','job_title'=>'Contable','source'=>'facebook','status'=>'contacted','priority'=>'high'],
  ['first_name'=>'Pedro','last_name'=>'Santos','email'=>'pedro.santos@example.com','phone'=>'+34 600 111 003','company'=>'RetailPro','job_title'=>'Gerente','source'=>'google_ads','status'=>'qualified','priority'=>'high'],
  ['first_name'=>'Carla','last_name'=>'Rivas','email'=>'carla.rivas@example.com','phone'=>'+34 600 111 004','company'=>'AutoParts','job_title'=>'Ventas','source'=>'referral','status'=>'new','priority'=>'medium'],
  ['first_name'=>'Diego','last_name'=>'Luna','email'=>'diego.luna@example.com','phone'=>'+34 600 111 005','company'=>'HealthCare','job_title'=>'Asesor','source'=>'instagram','status'=>'contacted','priority'=>'low'],
];

$inserted = 0; $skipped = 0; $errors = [];

foreach ($leads as $lead) {
  try {
    // Comprobar duplicados por email
    $exists = $db->count('SELECT COUNT(*) FROM leads WHERE email = ?', [$lead['email']]);
    if ($exists > 0) { $skipped++; continue; }

    $sql = 'INSERT INTO leads (first_name,last_name,email,phone,company,job_title,source,status,priority,created_at) 
            VALUES (:first_name,:last_name,:email,:phone,:company,:job_title,:source,:status,:priority,:created_at)';
    $ok = $db->execute($sql, [
      ':first_name'=>$lead['first_name'], ':last_name'=>$lead['last_name'], ':email'=>$lead['email'], ':phone'=>$lead['phone'],
      ':company'=>$lead['company'], ':job_title'=>$lead['job_title'], ':source'=>$lead['source'], ':status'=>$lead['status'],
      ':priority'=>$lead['priority'], ':created_at'=>$now
    ]);
    if ($ok) { $inserted++; }
    else { $errors[] = 'Fallo al insertar ' . $lead['email']; }
  } catch (Throwable $e) {
    $errors[] = $e->getMessage();
  }
}

echo json_encode(['success'=>true,'inserted'=>$inserted,'skipped'=>$skipped,'errors'=>$errors], JSON_UNESCAPED_UNICODE);
?>