<?php
// admin/get_cheques.php
header('Content-Type: application/json; charset=utf-8');

include __DIR__ . '/conexion3.php';

$account_id = isset($_GET['account_id']) ? (int)$_GET['account_id'] : 0;
$status     = isset($_GET['status']) ? trim($_GET['status']) : 'in';

if ($account_id <= 0) {
  echo json_encode(['ok' => false, 'msg' => 'account_id inválido', 'data' => []]);
  exit;
}

$status_sql = $conn->real_escape_string($status);

$sql = "
  SELECT cheque_id, numero, fecha, fecha_pago, importe, cuit, caja_id, status
  FROM cheques
  WHERE caja_id = $account_id AND status = '$status_sql'
  ORDER BY fecha_pago ASC, fecha ASC, cheque_id ASC
";
$rs = $conn->query($sql);

if (!$rs) {
  echo json_encode(['ok' => false, 'msg' => 'Error DB: '.$conn->error, 'data' => []]);
  exit;
}

$out = [];
while ($r = $rs->fetch_assoc()) {
  $out[] = [
    'cheque_id'  => (int)$r['cheque_id'],
    'numero'     => (string)$r['numero'],
    'fecha'      => (string)$r['fecha'],
    'fecha_pago' => (string)$r['fecha_pago'],
    'importe'    => (float)$r['importe'],
    'cuit'       => (string)$r['cuit'],
    'caja_id'    => (int)$r['caja_id'],
    'status'     => (string)$r['status'],
  ];
}

echo json_encode(['ok' => true, 'data' => $out], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
