<?php
ob_start();
session_start();
require_once __DIR__ . '/../_init.php';

// Verifico login y permiso
if (!is_loggedin()) {
    redirect('login.php');
}
if (user_group_id() != 1 && !has_permission('access', 'transfer')) {
    die('No tiene permiso para ver este comprobante.');
}

$transfer_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($transfer_id <= 0) {
    die('ID de comprobante inválido.');
}

$pdo = db();

// Cabecera: cheque_transfer_info + info de cuenta y usuario
$sql = "
    SELECT 
        t.*,
        ba_from.account_name AS from_account_name,
        ba_to.account_name   AS to_account_name,
        u.username           AS user_name
    FROM cheque_transfer_info t
    LEFT JOIN bank_accounts ba_from ON ba_from.id = t.from_account_id
    LEFT JOIN bank_accounts ba_to   ON ba_to.id   = t.to_account_id
    LEFT JOIN users u               ON u.id       = t.user_id
    WHERE t.id = ?
";
$st = $pdo->prepare($sql);
$st->execute([$transfer_id]);
$info = $st->fetch(PDO::FETCH_ASSOC);

if (!$info) {
    die('Comprobante no encontrado.');
}

// Detalle: cheques incluidos
$sqlDet = "
    SELECT *
    FROM cheque_transfer_item
    WHERE transfer_id = ?
    ORDER BY fecha_pago ASC, fecha ASC, id ASC
";
$stDet = $pdo->prepare($sqlDet);
$stDet->execute([$transfer_id]);
$items = $stDet->fetchAll(PDO::FETCH_ASSOC);

// Datos de la empresa (opcional, según tu tabla store)
$storeInfo = null;
try {
    $stStore = $pdo->query("SELECT * FROM store LIMIT 1");
    $storeInfo = $stStore->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Si no existe la tabla o columnas, simplemente ignoramos
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Rendición de Cheques #<?php echo (int)$info['id']; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
        }
        body {
            padding: 20px;
        }
        .comprobante-header {
            border-bottom: 2px solid #000;
            margin-bottom: 15px;
            padding-bottom: 10px;
        }
        .comprobante-title {
            font-size: 20px;
            font-weight: bold;
            text-transform: uppercase;
        }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="row comprobante-header">
        <div class="col-8">
            <?php if ($storeInfo): ?>
                <h4 class="mb-0">
                    <?php echo htmlspecialchars($storeInfo['store_name'] ?? ''); ?>
                </h4>
                <div>
                    CUIT: <?php echo htmlspecialchars($storeInfo['cuit'] ?? ''); ?><br>
                    <?php echo htmlspecialchars($storeInfo['address'] ?? ''); ?>
                </div>
            <?php else: ?>
                <h4 class="mb-0">TERRAPRO</h4>
                <div>comprobante interno de tesoreria</div>
            <?php endif; ?>
        </div>
        <div class="col-4 text-end">
            <div class="comprobante-title">Rendición de cheques</div>
            <div>N°: <strong><?php echo (int)$info['id']; ?></strong></div>
            <div>Fecha: <?php echo htmlspecialchars($info['created_at']); ?></div>
        </div>
    </div>

    <div class="row mb-3">
        <div class="col-6">
            <h6>Cuenta Origen</h6>
            <p class="mb-1">
                <strong><?php echo htmlspecialchars($info['from_account_name'] ?? ('Cuenta #' . $info['from_account_id'])); ?></strong><br>
                ID: <?php echo (int)$info['from_account_id']; ?>
            </p>
        </div>
        <div class="col-6">
            <h6>Cuenta Destino</h6>
            <p class="mb-1">
                <strong><?php echo htmlspecialchars($info['to_account_name'] ?? ('Cuenta #' . $info['to_account_id'])); ?></strong><br>
                ID: <?php echo (int)$info['to_account_id']; ?>
            </p>
        </div>
    </div>

    <div class="row mb-3">
        <div class="col-6">
            <h6>Responsable</h6>
            <p class="mb-1">
                Usuario: <strong><?php echo htmlspecialchars($info['user_name'] ?? ('ID ' . $info['user_id'])); ?></strong><br>
                Store ID: <?php echo (int)$info['store_id']; ?>
            </p>
        </div>
        <div class="col-6">
            <h6>Resumen</h6>
            <p class="mb-1">
                Cantidad de cheques: <strong><?php echo (int)$info['cheque_count']; ?></strong><br>
                Total rendido: <strong>$ <?php echo number_format((float)$info['total'], 2, ',', '.'); ?></strong>
            </p>
        </div>
    </div>

    <?php if (!empty($info['notes'])): ?>
        <div class="row mb-3">
            <div class="col-12">
                <h6>Observaciones</h6>
                <p><?php echo nl2br(htmlspecialchars($info['notes'])); ?></p>
            </div>
        </div>
    <?php endif; ?>

    <div class="row mb-3">
        <div class="col-12">
            <h6>Detalle de Cheques</h6>
            <div class="table-responsive">
                <table class="table table-sm table-bordered align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>N° Cheque</th>
                            <th>Fecha Emisión</th>
                            <th>Fecha Pago</th>
                            <th>Banco</th>
                            <th>CUIT</th>
                            <th class="text-end">Importe</th>
                            <th>Observaciones</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $suma = 0;
                    foreach ($items as $idx => $c):
                        $importe = (float)$c['importe'];
                        $suma += $importe;
                    ?>
                        <tr>
                            <td><?php echo $idx + 1; ?></td>
                            <td><?php echo htmlspecialchars($c['numero']); ?></td>
                            <td><?php echo htmlspecialchars($c['fecha']); ?></td>
                            <td><?php echo htmlspecialchars($c['fecha_pago']); ?></td>
                            <td><?php echo htmlspecialchars($c['banco']); ?></td>
                            <td><?php echo htmlspecialchars($c['cuit']); ?></td>
                            <td class="text-end">$ <?php echo number_format($importe, 2, ',', '.'); ?></td>
                            <td><?php echo nl2br(htmlspecialchars($c['observaciones'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="6" class="text-end">TOTAL</th>
                            <th class="text-end">
                                $ <?php echo number_format($suma, 2, ',', '.'); ?>
                            </th>
                            <th></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <div class="row mt-4 no-print">
        <div class="col-12 text-end">
            <button class="btn btn-primary" onclick="window.print();">Imprimir</button>
        </div>
    </div>

    <div class="row mt-5">
        <div class="col-6 text-center">
            ___________________________<br>
            Firma Entrega
        </div>
        <div class="col-6 text-center">
            ___________________________<br>
            Firma Recepción
        </div>
    </div>
</div>

</body>
</html>
