<?php
session_start();
header('Content-Type: application/json');
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(__DIR__)); }
require_once BASE_PATH . '/database/connection.php';

function columnExists($pdo, $table, $column){
  try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?");
    $stmt->execute([$table, $column]);
    return (bool)$stmt->fetchColumn();
  } catch (Throwable $e) { return false; }
}

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $clientId = isset($_SESSION['client_id']) ? intval($_SESSION['client_id']) : 0;
  if ($clientId <= 0) { throw new Exception('No autenticado'); }

  $action = $_GET['action'] ?? ($_POST['action'] ?? 'history');

  // Obtener gestor asignado
  $stmtC = $pdo->prepare('SELECT lead_id, assigned_to FROM clients WHERE id = ? LIMIT 1');
  $stmtC->execute([$clientId]);
  $c = $stmtC->fetch(PDO::FETCH_ASSOC);
  $managerId = null;
  if ($c) {
    if (!empty($c['assigned_to'])) { $managerId = (int)$c['assigned_to']; }
    elseif (!empty($c['lead_id'])) {
      $stL = $pdo->prepare('SELECT assigned_to FROM leads WHERE id = ? LIMIT 1');
      $stL->execute([(int)$c['lead_id']]);
      $managerId = (int)$stL->fetchColumn();
    }
  }
  if (!$managerId) { throw new Exception('Sin gestor asignado'); }

  // Buscar ticket de chat activo
  $stmtT = $pdo->prepare("SELECT id FROM support_tickets WHERE client_id = ? AND subject = 'Chat con gestor' AND status IN ('open','pending') ORDER BY created_at DESC LIMIT 1");
  $stmtT->execute([$clientId]);
  $ticketId = (int)$stmtT->fetchColumn();
  if (!$ticketId) {
    $assignedExists = columnExists($pdo, 'support_tickets', 'assigned_to');
    if ($assignedExists) {
      $stNew = $pdo->prepare("INSERT INTO support_tickets (client_id, subject, message, status, priority, assigned_to, created_at) VALUES (?, 'Chat con gestor', '', 'open', 'medium', ?, NOW())");
      $stNew->execute([$clientId, $managerId]);
    } else {
      $stNew = $pdo->prepare("INSERT INTO support_tickets (client_id, subject, message, status, priority, created_at) VALUES (?, 'Chat con gestor', '', 'open', 'medium', NOW())");
      $stNew->execute([$clientId]);
    }
    $ticketId = (int)$pdo->lastInsertId();
  }

  if ($action === 'send') {
    $msg = trim($_POST['message'] ?? '');
    if ($msg === '') { throw new Exception('Mensaje vacío'); }
    $stm = $pdo->prepare('INSERT INTO support_ticket_messages (ticket_id, sender_type, message, created_at) VALUES (?, "client", ?, NOW())');
    $stm->execute([$ticketId, $msg]);
    try {
      if (!empty($c['lead_id'])) {
        $stA = $pdo->prepare('INSERT INTO lead_activities (lead_id, type, subject, description, status, created_by, created_at) VALUES (?, "system", ?, ?, "completed", ?, NOW())');
        $stA->execute([(int)$c['lead_id'], 'Mensaje del cliente', $msg, (int)$managerId]);
      }
    } catch (Throwable $e) {}
  }

  // Historia del chat
  $stmH = $pdo->prepare('SELECT sender_type, message, created_at FROM support_ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC');
  $stmH->execute([$ticketId]);
  $msgs = $stmH->fetchAll(PDO::FETCH_ASSOC);

  // Datos del gestor
  $stU = $pdo->prepare('SELECT first_name, last_name, email FROM users WHERE id = ? LIMIT 1');
  $stU->execute([$managerId]);
  $mgr = $stU->fetch(PDO::FETCH_ASSOC);

  echo json_encode(['success'=>true,'ticket_id'=>$ticketId,'manager'=>$mgr,'messages'=>$msgs]);
} catch (Throwable $e) {
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
?>
