<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
if (!isLoggedIn()) { header('Location: ' . route_url(['module'=>'auth','action'=>'login'])); exit; }

$db = Database::getInstance();
$pdo = $db->getConnection();

header('Content-Type: text/plain; charset=utf-8');

try {
  $pdo->prepare('CREATE TABLE IF NOT EXISTS client_activities (
    id INT AUTO_INCREMENT PRIMARY KEY,
    client_id INT NOT NULL,
    type ENUM("call","email","meeting","note","task","system") NOT NULL,
    subject VARCHAR(255) NOT NULL,
    description TEXT,
    status ENUM("pending","completed","cancelled") DEFAULT "completed",
    scheduled_at DATETIME NULL,
    duration_min INT NULL,
    completed_at DATETIME NULL,
    created_by INT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE,
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_client_id (client_id), INDEX idx_type (type), INDEX idx_status (status), INDEX idx_scheduled_at (scheduled_at), INDEX idx_created_by (created_by), INDEX idx_created_at (created_at)
  ) ENGINE=InnoDB')->execute();
} catch (Throwable $e) { echo "Error preparando tabla: " . $e->getMessage(); exit; }

$countCopied = 0; $countClients = 0;

// Estrategia: usar lead_id si existe; si no, buscar lead por email
$clients = $pdo->query('SELECT id, lead_id, email FROM clients')->fetchAll(PDO::FETCH_ASSOC);
foreach ($clients as $c) {
  $countClients++;
  $clientId = (int)$c['id'];
  $leadId = (int)($c['lead_id'] ?? 0);
  if ($leadId <= 0) {
    // buscar por email
    $st = $pdo->prepare('SELECT id FROM leads WHERE email = ? ORDER BY created_at DESC LIMIT 1');
    $st->execute([ $c['email'] ]);
    $leadId = (int)($st->fetchColumn() ?: 0);
  }
  if ($leadId <= 0) { continue; }
  // copiar actividades del lead
  $acts = $pdo->prepare('SELECT type, subject, description, status, scheduled_at, duration_min, completed_at, created_by, created_at FROM lead_activities WHERE lead_id = ?');
  $acts->execute([$leadId]);
  $rows = $acts->fetchAll(PDO::FETCH_ASSOC);
  foreach ($rows as $a) {
    $exists = $pdo->prepare('SELECT 1 FROM client_activities WHERE client_id=? AND subject=? AND created_at=? LIMIT 1');
    $exists->execute([$clientId, $a['subject'], $a['created_at']]);
    if (!$exists->fetchColumn()) {
      $ins = $pdo->prepare('INSERT INTO client_activities (client_id, type, subject, description, status, scheduled_at, duration_min, completed_at, created_by, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)');
      $ins->execute([$clientId, $a['type'], $a['subject'], $a['description'], $a['status'], $a['scheduled_at'], $a['duration_min'], $a['completed_at'], $a['created_by'], $a['created_at']]);
      $countCopied++;
    }
  }
}

echo "Clientes procesados: $countClients\n";
echo "Actividades copiadas: $countCopied\n";
?>
