<?php
// views/pages/raspadita/api/cobro_canillita_insert.php
// ✅ INSERT COBRO CANILLITA -> tbr_coordinador_saldo
// ✅ SI tipo_pago = CREDITO -> SUMA total_pagar a tbr_canillita.saldo

declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Método no permitido'], JSON_UNESCAPED_UNICODE);
  exit;
}

function jexit(array $payload, int $code=200): void {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE);
  exit;
}

function read_json(): array {
  $raw = file_get_contents('php://input');
  if (!$raw) return [];
  $j = json_decode($raw, true);
  return is_array($j) ? $j : [];
}

function ip_client(): string {
  return substr((string)($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'), 0, 45);
}

function dec($v): float {
  if (is_string($v)) $v = str_replace(',', '.', $v);
  return round((float)$v, 2);
}

try {
  require_once __DIR__ . '/../../conex.php';
  $db = $conn ?? null;
  if (!$db instanceof mysqli) jexit(['success'=>false,'message'=>'Sin conexión BD'], 500);

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

  $in = read_json();

  $id_admin = (int)($_SESSION['idusuario'] ?? $in['id_admin'] ?? 0);

  $id_canillita   = (int)($in['id_canillita'] ?? 0);
  $num_raspaditas = (int)($in['num_raspaditas'] ?? 0);
  $subtotal       = dec($in['subtotal'] ?? 0);
  $descuento      = dec($in['descuento'] ?? 0);
  $total_pagar    = dec($in['total_pagar'] ?? 0);

  $tipo_pago = strtoupper(trim((string)($in['tipo_pago'] ?? 'EFECTIVO')));
  if (!in_array($tipo_pago, ['EFECTIVO','CREDITO'], true)) $tipo_pago = 'EFECTIVO';

  $observacion = trim((string)($in['observacion'] ?? 'COBRO CANILLITA'));
  if ($observacion === '') $observacion = 'COBRO CANILLITA';

  if ($id_canillita <= 0) jexit(['success'=>false,'message'=>'id_canillita inválido'], 400);
  if ($num_raspaditas <= 0) jexit(['success'=>false,'message'=>'num_raspaditas inválido'], 400);

  $calc_total = round($subtotal - $descuento, 2);
  if (abs($calc_total - $total_pagar) > 0.02) $total_pagar = $calc_total;

  if ($total_pagar < 0) jexit(['success'=>false,'message'=>'total_pagar inválido'], 400);

  $fecha_hora = date('Y-m-d H:i:s');
  $ip = ip_client();

  // ==========================
  // ✅ TRANSACCIÓN
  // ==========================
  $db->begin_transaction();

  // ✅ VALIDAR CANILLITA + leer saldo actual (bloqueo FOR UPDATE)
  $stmt = $db->prepare("SELECT id, saldo FROM tbr_canillita WHERE id=? AND activo=1 LIMIT 1 FOR UPDATE");
  $stmt->bind_param("i", $id_canillita);
  $stmt->execute();
  $res = $stmt->get_result();
  $row = $res->fetch_assoc();
  $stmt->close();

  if (!$row) {
    $db->rollback();
    jexit(['success'=>false,'message'=>'Canillita no existe o está inactivo'], 404);
  }

  $saldo_anterior = dec($row['saldo'] ?? 0);
  $saldo_nuevo = $saldo_anterior;

  // ✅ INSERT COBRO
  $sql = "INSERT INTO tbr_coordinador_saldo
          (fecha_hora, num_raspaditas, subtotal, descuento, total_pagar,
           observacion, id_admin, ip, created_at, tipo_pago, id_canillita)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)";

  $stmt = $db->prepare($sql);
  $stmt->bind_param(
    "sidddsissi",
    $fecha_hora,
    $num_raspaditas,
    $subtotal,
    $descuento,
    $total_pagar,
    $observacion,
    $id_admin,
    $ip,
    $tipo_pago,
    $id_canillita
  );

  if (!$stmt->execute()) {
    $err = $stmt->error;
    $stmt->close();
    $db->rollback();
    jexit(['success'=>false,'message'=>'Error al insertar cobro', 'detail'=>$err], 500);
  }

  $newId = $stmt->insert_id;
  $stmt->close();

  // ✅ SI ES CRÉDITO: sumar total_pagar al saldo del canillita
  if ($tipo_pago === 'CREDITO' && $total_pagar > 0) {
    $stmt = $db->prepare("UPDATE tbr_canillita SET saldo = ROUND(COALESCE(saldo,0) + ?, 2) WHERE id=? LIMIT 1");
    $stmt->bind_param("di", $total_pagar, $id_canillita);
    if (!$stmt->execute()) {
      $err = $stmt->error;
      $stmt->close();
      $db->rollback();
      jexit(['success'=>false,'message'=>'Error al actualizar saldo (CRÉDITO)', 'detail'=>$err], 500);
    }
    $stmt->close();

    $saldo_nuevo = round($saldo_anterior + $total_pagar, 2);
  }

  $db->commit();

  jexit([
    'success'        => true,
    'id'             => $newId,
    'message'        => 'Cobro registrado correctamente',
    'tipo_pago'      => $tipo_pago,
    'saldo_anterior' => $saldo_anterior,
    'saldo_nuevo'    => $saldo_nuevo
  ]);

} catch (Throwable $e) {
  if (isset($db) && $db instanceof mysqli) {
    try { $db->rollback(); } catch(Throwable $_) {}
  }
  jexit(['success'=>false,'message'=>'Error interno','detail'=>$e->getMessage()], 500);
}
