<?php
ob_start();
session_start();
require_once("../_init.php"); // ajust� la ruta si tu ajax/ est� en otra carpeta

header('Content-Type: text/html; charset=UTF-8');

// Seguridad b�sica
if (!is_loggedin()) {
  http_response_code(401);
  echo '<div class="alert alert-danger">'.trans('error_login').'</div>';
  exit();
}
if (user_group_id() != 1 && !has_permission('access','read_bank_account_sheet')) {
  http_response_code(403);
  echo '<div class="alert alert-danger">'.trans('error_read_permission').'</div>';
  exit();
}

// Par�metros
$account_id = isset($_GET['account_id']) ? (int)$_GET['account_id'] : 0;
if ($account_id <= 0) {
  http_response_code(422);
  echo '<div class="alert alert-warning">Par�metro account_id inv�lido.</div>';
  exit();
}

// Cajas que deben mostrar la tabla cheques (ajust� seg�n tus IDs)
$CHEQUE_ACCOUNT_IDS = [2,17,16,18,19];

// Traer nombre de la cuenta
try {
  $stmt = db()->prepare("SELECT account_name FROM bank_accounts WHERE id = ?");
  $stmt->execute([$account_id]);
  $acc = $stmt->fetch(PDO::FETCH_ASSOC);
  $account_name = $acc ? $acc['account_name'] : ('Cuenta #'.$account_id);
} catch (Exception $e) {
  $account_name = 'Cuenta #'.$account_id;
}

// Si es una caja de cheques => mostrar cheques
if (in_array($account_id, $CHEQUE_ACCOUNT_IDS, true)) {

  $stmt = db()->prepare("
    SELECT cheque_id, numero, fecha, fecha_pago, importe, cuit, tipo_cheque, banco, status, observaciones
    FROM cheques
    WHERE caja_id = ? AND status = 'in'
    ORDER BY fecha DESC, cheque_id DESC
    LIMIT 500
  ");
  $stmt->execute([$account_id]);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  // Total
  $total = 0;
  foreach ($rows as $r) {
  
  if($r['status'] == 'in'){
    $total += (float)$r['importe'];
  }
  }

  ?>
  <div>
    <h4 style="margin-top:0">Cheques en: <?php echo htmlspecialchars($account_name); ?></h4>
    <p class="text-muted">Mostrando hasta 500 resultados mas recientes.</p>

    <?php if (!$rows): ?>
      <div class="alert alert-info">No hay cheques registrados para esta caja.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-bordered table-striped table-condensed" style="margin-bottom:8px">
          <thead>
            <tr class="info">
              <th>#</th>
              <th>Numero</th>
              <th>Fecha</th>
              <th>Fecha cobro</th>
              <th>Importe</th>
              <th>CUIT</th>
              <th>Banco</th>
              <th>Tipo</th>
              <th>Estado</th>
              <th>Obs.</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($rows as $i => $r): ?>
            <tr>
              <td><?php echo (int)$r['cheque_id']; ?></td>
              <td><?php echo htmlspecialchars($r['numero']); ?></td>
              <td><?php echo htmlspecialchars($r['fecha']); ?></td>
              <td><?php echo htmlspecialchars($r['fecha_pago']); ?></td>
              <td><?php echo currency_format((float)$r['importe']); ?></td>
              <td><?php echo htmlspecialchars($r['cuit']); ?></td>
              <td><?php echo htmlspecialchars($r['banco']); ?></td>
              <td><?php echo htmlspecialchars($r['tipo_cheque']); ?></td>
              <td><?php echo htmlspecialchars($r['status']); ?></td>
              <td><?php echo htmlspecialchars($r['observaciones']); ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="4" class="text-right">Total</th>
              <th><?php echo currency_format($total); ?></th>
              <th colspan="5"></th>
            </tr>
          </tfoot>
        </table>
      </div>
    <?php endif; ?>
  </div>
  <?php

  exit();
}

// Si NO es caja de cheques, mostramos resumen simple (pod�s extenderlo a movimientos)
try {
  $stmt = db()->prepare("
    SELECT ba.account_name, ba.account_no, ba.account_details,
           s.deposit, s.withdraw, s.transfer_from_other, s.transfer_to_other
    FROM bank_accounts ba
    LEFT JOIN bank_account_to_store s ON (ba.id = s.account_id AND s.store_id = ?)
    WHERE ba.id = ?
    LIMIT 1
  ");
  $stmt->execute([store_id(), $account_id]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
  $row = false;
}

?>
<div>
  <h4 style="margin-top:0">Detalle: <?php echo htmlspecialchars($account_name); ?></h4>
  <?php if (!$row): ?>
    <div class="alert alert-warning">No se encontro informaci�n adicional para esta cuenta.</div>
  <?php else:
    $balance = ($row['deposit'] + $row['transfer_from_other']) - ($row['withdraw'] + $row['transfer_to_other']);
  ?>
    <div class="table-responsive">
      <table class="table table-bordered table-striped table-condensed">
        <tbody>
          <tr><th class="w-30">N Cuenta</th><td class="w-70"><?php echo htmlspecialchars($row['account_no']); ?></td></tr>
          <tr><th>Ingresos</th><td><?php echo currency_format($row['deposit']); ?></td></tr>
          <tr><th>Egresos</th><td><?php echo currency_format($row['withdraw']); ?></td></tr>
          <tr><th>Transferencias recibidas</th><td><?php echo currency_format($row['transfer_from_other']); ?></td></tr>
          <tr><th>Transferencias emitidas</th><td><?php echo currency_format($row['transfer_to_other']); ?></td></tr>
          <tr class="info"><th>Balance</th><td><b><?php echo currency_format($balance); ?></b></td></tr>
        </tbody>
      </table>
    </div>
    <?php if (!empty($row['account_details'])): ?>
      <p class="text-muted"><b>Detalle:</b> <?php echo nl2br(htmlspecialchars($row['account_details'])); ?></p>
    <?php endif; ?>
  <?php endif; ?>
</div>
