<?php
// api/facturas_detalle_guardar.php — Inserta detalle y recalcula totales
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../conex.php';

$db = $conn ?? ($conex ?? null);
if (!$db) { echo json_encode(['success'=>false,'message'=>'Sin conexión']); exit; }

mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

/* ===== Entradas ===== */
$id_facturainfo = (int)($_POST['idfactura'] ?? $_POST['id_facturainfo'] ?? 0);
if ($id_facturainfo <= 0) { echo json_encode(['success'=>false,'message'=>'Factura inválida']); exit; }

$numerod    = trim((string)($_POST['numerod'] ?? ''));                 // opcional
$id_estado  = (int)($_POST['id_estado'] ?? 1);
$id_datadai = isset($_POST['id_datadai']) ? (int)$_POST['id_datadai'] :
              (isset($_POST['iddatadai']) ? (int)$_POST['iddatadai'] : null);

$cantidad   = (int)($_POST['cantidad'] ?? 1);
$valorfob   = ($_POST['valorfob'] ?? $_POST['fobunitario'] ?? '') !== '' ? (float)($_POST['valorfob'] ?? $_POST['fobunitario']) : null;
$flete      = ($_POST['flete'] ?? $_POST['transporte'] ?? '') !== '' ? (float)($_POST['flete'] ?? $_POST['transporte']) : null;
$seguro     = ($_POST['seguro'] ?? '') !== '' ? (float)$_POST['seguro'] : null;
$valoradua  = ($_POST['valoradua'] ?? $_POST['valoraduana'] ?? '') !== '' ? (float)($_POST['valoradua'] ?? $_POST['valoraduana']) : null;
$condicion  = 1;

if ($cantidad <= 0) $cantidad = 1;

mysqli_begin_transaction($db, MYSQLI_TRANS_START_READ_WRITE);
try {
  // Insert detalle
  $sql = "INSERT INTO detallefactura
            (numerod, id_estado, id_datadai, cantidad, valorfob, flete, seguro, valoradua, id_facturainfo, condicion)
          VALUES (?,?,?,?,?,?,?,?,?,?)";
  $st = mysqli_prepare($db, $sql);
  mysqli_stmt_bind_param(
    $st,
    'siiiddddid',
    $numerod,
    $id_estado,
    $id_datadai,
    $cantidad,
    $valorfob,
    $flete,
    $seguro,
    $valoradua,
    $id_facturainfo,
    $condicion
  );
  if (!mysqli_stmt_execute($st)) {
    throw new Exception('No se pudo guardar el detalle. SQLSTATE ' . mysqli_sqlstate($db) . ' ' . mysqli_error($db));
  }

  // Recalcular agregados de la cabecera desde detallefactura
  $sum = mysqli_query($db, "
    SELECT
      COALESCE(SUM(cantidad),0)       AS cantidad,
      COALESCE(SUM(valorfob),0)       AS totalfob,
      COALESCE(SUM(flete),0)          AS totalflete,
      COALESCE(SUM(seguro),0)         AS totalseguro
    FROM detallefactura
    WHERE id_facturainfo = {$id_facturainfo} AND condicion = 1
  ");
  $agg = mysqli_fetch_assoc($sum) ?: ['cantidad'=>0,'totalfob'=>0,'totalflete'=>0,'totalseguro'=>0];
  $cantidadAgg   = (int)$agg['cantidad'];
  $totalfobAgg   = (float)$agg['totalfob'];
  $totalfleteAgg = (float)$agg['totalflete'];
  $totalseguroAgg= (float)$agg['totalseguro'];
  $totalAgg      = $totalfobAgg + $totalfleteAgg + $totalseguroAgg;

  $up = mysqli_prepare($db, "
    UPDATE tb_facturainfo
    SET cantidad=?, totalfob=?, totalflete=?, totalseguro=?, total=?
    WHERE idfacturainfo=?
  ");
  mysqli_stmt_bind_param($up, 'iddddi', $cantidadAgg, $totalfobAgg, $totalfleteAgg, $totalseguroAgg, $totalAgg, $id_facturainfo);
  if (!mysqli_stmt_execute($up)) {
    throw new Exception('No se pudieron actualizar totales.');
  }

  mysqli_commit($db);
  echo json_encode(['success'=>true]);
} catch (Throwable $e) {
  mysqli_rollback($db);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
