<?php
session_start();
include '../includes/session_control.php';

// Evitar caché del lado del servidor para respuestas dinámicas
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Expires: 0');

if (!isset($_SESSION['user'])) {
  http_response_code(401);
  echo json_encode(['rows' => '', 'totalCount' => 0, 'error' => 'No autenticado']);
  exit;
}

require __DIR__ . '/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

// 1) Parámetros
$limit  = isset($_GET['limit'])  ? intval($_GET['limit'])  : 50;
$page   = isset($_GET['page'])   ? intval($_GET['page'])   : 1;
// Normalizar
$limit = max(1, min(200, $limit));
$page = max(1, $page);
$search = isset($_GET['search']) ? trim((string)$_GET['search']) : '';
$pending = isset($_GET['pending']) ? intval($_GET['pending']) : 0;
$agendaDays = isset($_GET['agendaDays']) ? intval($_GET['agendaDays']) : 0;
$estado = isset($_GET['estado']) ? intval($_GET['estado']) : 0;
$view = isset($_GET['view']) ? trim((string)$_GET['view']) : '';

$url = $base . '/api/cotizaciones?limit=' . urlencode((string)$limit)
  . '&page=' . urlencode((string)$page)
  . '&search=' . urlencode($search);

if ($estado > 0) {
  $url .= '&estado=' . urlencode((string)$estado);
}

if ($agendaDays > 0) {
  $url .= '&agendaDays=' . urlencode((string)max(1, min(365, $agendaDays)));
} elseif ($pending === 1) {
  $url .= '&pending=1';
}

$r = cpn_node_request('GET', $url, $token);
if (!isset($r['ok']) || $r['ok'] !== true) {
  http_response_code($r['_http'] ?? 500);
  $msg = $r['error']['message'] ?? 'Error consultando cotizaciones.';
  echo json_encode(['rows' => '', 'totalCount' => 0, 'error' => $msg]);
  exit;
}

$data = $r['data'] ?? [];
$rows = $data['rows'] ?? [];
$estados = $data['estados'] ?? [];
$totalCount = (int)($data['totalCount'] ?? 0);

$rowsHtml = '';
$idx = 0;

function cpn_fmt_fecha_ui($value)
{
  $s = trim((string)($value ?? ''));
  if ($s === '' || $s === '0000-00-00 00:00:00') return '';
  $ts = strtotime($s);
  if (!$ts) return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');

  $mesesAbc = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
  $dia = date('j', $ts);
  $mes = $mesesAbc[(int)date('n', $ts) - 1] ?? date('M', $ts);
  $anio2 = date('y', $ts);
  $hora = date('g:i a', $ts);
  return "{$dia}-{$mes}-{$anio2} {$hora}";
}

foreach ($rows as $row) {
  $idx++;
  $zebra = ($idx % 2 === 0) ? 'zebra-even' : 'zebra-odd';

  $id = (int)($row['id'] ?? 0);
  $fecha = cpn_fmt_fecha_ui($row['fechaCreacion'] ?? '');
  $tipo = htmlspecialchars((string)($row['tipoNombre'] ?? ''), ENT_QUOTES, 'UTF-8');
  $nombre = htmlspecialchars((string)($row['nombre'] ?? ''), ENT_QUOTES, 'UTF-8');
  $apellido = htmlspecialchars((string)($row['apellido'] ?? ''), ENT_QUOTES, 'UTF-8');
  $telefono = htmlspecialchars((string)($row['telefono'] ?? ''), ENT_QUOTES, 'UTF-8');
  $dep = htmlspecialchars((string)($row['departamento'] ?? ''), ENT_QUOTES, 'UTF-8');
  $ciu = htmlspecialchars((string)($row['ciudad'] ?? ''), ENT_QUOTES, 'UTF-8');
  $estadoNombre = htmlspecialchars((string)($row['estadoNombre'] ?? ''), ENT_QUOTES, 'UTF-8');
  $respNombre = htmlspecialchars((string)($row['responsableNombre'] ?? ''), ENT_QUOTES, 'UTF-8');
  $respApellido = htmlspecialchars((string)($row['responsableApellido'] ?? ''), ENT_QUOTES, 'UTF-8');
  $responsable = trim("{$respNombre} {$respApellido}");
  $idVenta = (int)($row['idVenta'] ?? 0);

  $pendienteSeguimiento = !empty($row['pendienteSeguimiento']);
  $vencidaSinSeguimiento = !empty($row['vencidaSinSeguimiento']);
  $fechaProximoSeguimiento = $row['fechaProximoSeguimiento'] ?? '';
  $fechaVencimiento = $row['fechaVencimiento'] ?? '';

  $cliente = trim("{$nombre} {$apellido}");
  if ($cliente === '') $cliente = $nombre ?: $apellido;
  $clienteHtml = htmlspecialchars($cliente, ENT_QUOTES, 'UTF-8');
  if ($telefono !== '') {
    $clienteHtml .= "<br><small class=\"text-muted\">{$telefono}</small>";
  }

  $ciudadHtml = trim("{$ciu} - {$dep}");
  $ciudadHtml = htmlspecialchars($ciudadHtml, ENT_QUOTES, 'UTF-8');

  // Vista reducida para widget de pendientes en el dashboard
  if ($view === 'pending_widget') {
    $fechaProxUi = cpn_fmt_fecha_ui($fechaProximoSeguimiento);

    if ($fechaProxUi === '') {
      $fechaProxUi = '<span class="text-muted">—</span>';
    }

    $clienteAttr = htmlspecialchars($cliente, ENT_QUOTES, 'UTF-8');

    $rowsHtml .= "
      <tr class='{$zebra}'>
        <td class='text-center'>{$id}</td>
        <td>{$clienteHtml}</td>
        <td class='text-center'>{$fechaProxUi}</td>
        <td class='text-center'>
          <a href='/cotizaciones/detalle_cotizacion.php?id={$id}' class='btn btn-primary btn-sm'>Ver</a>
          <button type='button' class='btn btn-outline-secondary btn-sm ml-1 js-cot-notas' data-id='{$id}' data-cliente='{$clienteAttr}'>Notas</button>
        </td>
      </tr>
    ";
    continue;
  }

  $rowsHtml .= "
    <tr class='cot-main {$zebra}'>
      <td class='text-center'>{$id}</td>
      <td class='text-center'>{$fecha}</td>
      <td class='text-center'>{$tipo}</td>
      <td>{$clienteHtml}</td>
      <td>{$ciudadHtml}</td>
      <td>
        {$estadoNombre}
  ";

  if ($pendienteSeguimiento) {
    $fechaProxUi = cpn_fmt_fecha_ui($fechaProximoSeguimiento);
    $rowsHtml .= "<br><span class='badge badge-warning'>Pendiente</span>";
    if ($fechaProxUi !== '') {
      $rowsHtml .= " <small class='text-muted'>{$fechaProxUi}</small>";
    }
  }

  if ($vencidaSinSeguimiento) {
    $fechaVenceUi = cpn_fmt_fecha_ui($fechaVencimiento);
    $rowsHtml .= "<br><span class='badge badge-danger'>Vencida sin notas</span>";
    if ($fechaVenceUi !== '') {
      $rowsHtml .= " <small class='text-muted'>{$fechaVenceUi}</small>";
    }
  }

  $rowsHtml .= "
      </td>
      <td>" . ($responsable !== '' ? $responsable : '') . "</td>
      <td class='text-center'>
  ";

  if ($idVenta <= 0) {
    $rowsHtml .= "<button class='btn btn-success btn-sm agregar-ventas' data-id='{$id}'>Agregar a ventas</button>";
    $rowsHtml .= "<a href='/cotizaciones/detalle_cotizacion.php?id={$id}' class='btn btn-primary btn-sm ml-1'>Editar</a>";
    $rowsHtml .= "<button class='btn btn-info btn-sm ml-1 detalle-toggle' data-bs-toggle='collapse' data-bs-target='#detalle-{$id}' data-id='{$id}'>Detalle</button>";
  } else {
    // Ya está vinculada a una venta: no permitir re-agregar por error.
    $rowsHtml .= "<a href='/cotizaciones/detalle_cotizacion.php?id={$id}' class='btn btn-primary btn-sm'>Editar</a>";
    $rowsHtml .= "<button class='btn btn-info btn-sm ml-1 detalle-toggle' data-bs-toggle='collapse' data-bs-target='#detalle-{$id}' data-id='{$id}'>Detalle</button>";
  }

  $rowsHtml .= "
      </td>
      <td class='text-center'>";

  if ($idVenta > 0) {
    $rowsHtml .= "<a href='/ventas/venta.php?id={$idVenta}'>{$idVenta}</a>";
  }

  $rowsHtml .= "
      </td>
    </tr>
    ";

  $rowsHtml .= "
    <tr id='detalle-{$id}' class='cot-detail collapse {$zebra}'>
      <td colspan='9'>
        <table class='table table-sm mb-0'>
          <thead>
            <tr>
              <th class='text-center'>Referencia</th><th>Producto</th><th class='text-right'>Cant.</th><th class='text-right'>Precio</th>
            </tr>
          </thead>
          <tbody id='items-{$id}'></tbody>
        </table>
      </td>
    </tr>
    ";
}

// 4) Devolver JSON
echo json_encode([
  'rows'       => $rowsHtml,
  'totalCount' => $totalCount
]);


