<?php
session_start();

if (!isset($_SESSION['usuario'])) {
    header("Location: st_acceso.php");
    exit;
}

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once("st_conexion.php");

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    die("Error de conexión: " . $e->getMessage());
}

$usuarioSis = $_SESSION['usuario'];

/* ===========================
   Obtener nombre real usuario
=========================== */
$sqlUser = "SELECT NOMBRE, APELLIDO_PATERNO 
            FROM HE_USUARIOS 
            WHERE USUARIO_SIS = :usr";
$stmtUser = $pdo->prepare($sqlUser);
$stmtUser->execute(['usr' => $usuarioSis]);
$usr = $stmtUser->fetch();

$usuarioNombreMostrar = $usr
    ? $usr['NOMBRE'] . ' ' . $usr['APELLIDO_PATERNO']
    : $usuarioSis;

/* ===============================
   CONSULTA DE PRÉSTAMOS HDR
===============================*/

$sqlHDR = "
    SELECT 
        H.*,
        UE.NOMBRE AS ENT_NOM,
        UE.APELLIDO_PATERNO AS ENT_APE,
        UR.NOMBRE AS REC_NOM,
        UR.APELLIDO_PATERNO AS REC_APE
    FROM HE_PRESTAMO_HDR H
    LEFT JOIN HE_USUARIOS UE ON UE.ID_USUARIO = H.ID_USUARIO_ENTREGA
    LEFT JOIN HE_USUARIOS UR ON UR.ID_USUARIO = H.ID_USUARIO_RECIBE
    ORDER BY H.ID DESC
";

$stmtHDR = $pdo->query($sqlHDR);
$headers = $stmtHDR->fetchAll();

/* ============================
   OBTENER DETALLES CON SERIE
============================ */
$sqlDTL = "
    SELECT 
        D.*, 
        H.SERIE 
    FROM HE_PRESTAMO_DTL D
    LEFT JOIN HE_MAESTRO H ON H.CLAVE = D.CLAVE_PRODUCTO
    WHERE D.ID_PRESTAMO = :id
";

$stmtDTL = $pdo->prepare($sqlDTL);

$detalles = [];
foreach ($headers as $h) {
    $stmtDTL->execute(['id' => $h['ID']]);
    $detalles[$h['ID']] = $stmtDTL->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Visualizar Préstamos</title>
<link rel="icon" href="Iconos/rf_icono_vineta.png" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: 'Helvetica', sans-serif;
    background-color: #f3f4f8;
    color: #333;
}

.fondo-leyenda {
    background-color: #ffcc00;
    text-align: center;
    padding: 5px;
    font-size: 13px;
    font-weight: bold;
}

.topbar {
    width: 100%;
    background-color: #1D3C7D;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 30px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    position: fixed;
    top: 0;
    z-index: 1000;
    height: 50px;
}

.topbar .title { position: absolute; left: 20px; font-size: 20px; }
.topbar .logout { position: absolute; right: 20px; }
.topbar .logout button {
    display: flex; align-items: center; gap: 6px;
    background: #bd0909; border: none; padding: 6px 14px;
    border-radius: 6px; color: white; font-size: 13px;
}
.topbar .logout button:hover { background-color: red; }

.encabezado-formulario {
    margin-top: 100px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    background-color: white;
    border-radius: 10px;
    max-width: 1600px;
    margin-left: auto;
    margin-right: auto;
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}

.contenedor-menu {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    max-width: 1800px;
    margin: 20px auto;
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}

table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}
th, td {
    padding: 8px 12px;
    border: 1px solid #ccc;
}

.fila-click:hover { background: #eef3ff; cursor: pointer; }

/* Tabla detalle oculta */
.detalle {
    display: none;
    background: #f8f9fe;
}
.detalle td {
    background: #f8f9fe;
}

/* Badges de Estado */
.badge {
    padding: 3px 8px;
    border-radius: 8px;
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.badge-activo { background-color: #28a745; }       /* Verde */
.badge-cerrado { background-color: #dc3545; }      /* Rojo */
.badge-parcial { background-color: #ffc107; color: #212529; } /* Naranja */
.badge-observ { background-color: #17a2b8; }      /* Azul */
.badge-serie { background-color: #6c757d; color: #fff; } /* Gris oscuro */
</style>
</head>

<body>

<div class="fondo-leyenda">Sistema en Modo Pruebas - @Sergio Bravo +56 9 46237231</div>

<!-- TOPBAR -->
<div class="topbar">
    <div class="title">StockTools</div>
    <div class="user-info">Bienvenido, <?= htmlspecialchars($usuarioNombreMostrar) ?></div>

    <div class="logout">
        <button onclick="location.href='st_logout.php'">
            <img src="Iconos/st_icono_salir.png" width="30" height="30"> Cerrar Sesión
        </button>
    </div>
</div>

<!-- ENCABEZADO -->
<div class="encabezado-formulario">
    <div class="titulo-menu" style="display:flex;align-items:center;gap:10px;">
        <img src="Iconos/rf_icono_mbuscar.png" width="35" height="35">
        <h1 style="font-size:18px;">Visualización de Préstamos</h1>
    </div>

    <button onclick="location.href='st_menuppl.php'"
            style="background:#0c4896;color:white;border:none;border-radius:6px;padding:10px 15px;">
        Volver al Menú Principal
    </button>
</div>

<!-- TABLA PRINCIPAL -->
<div class="contenedor-menu">

<table>
<thead>
<tr>
    <th>ID</th>
    <th>Usuario Entrega</th>
    <th>Usuario Recibe</th>
    <th>Fecha/Hora Inicio</th>
    <th>Fecha/Hora Fin</th>
    <th>Nota</th>
    <th>Estado</th>
</tr>
</thead>

<tbody>
<?php foreach ($headers as $h): ?>
 <tr class="fila-click" data-id="<?= $h['ID'] ?>">
    <td><?= $h['ID'] ?></td>
    <td><?= htmlspecialchars($h['ENT_NOM'] . " " . $h['ENT_APE']) ?></td>
    <td><?= htmlspecialchars($h['REC_NOM'] . " " . $h['REC_APE']) ?></td>
    <td><?= $h['FECHA_INICIO'] . " " . $h['HORA_INICIO'] ?></td>
    <td><?= $h['FECHA_FIN'] ? $h['FECHA_FIN'] . " " . $h['HORA_FIN'] : "-" ?></td>
    <td><?= htmlspecialchars($h['NOTA']) ?></td>
    <td>
        <?php
        switch($h['ESTADO']) {
            case 1:
                echo '<span class="badge badge-activo">Activo</span>';
                break;
            case 2:
                echo '<span class="badge badge-cerrado">Cerrado</span>';
                break;
            case 3:
                echo '<span class="badge badge-parcial">Devolución parcial</span>';
                break;
            case 4:
                echo '<span class="badge badge-observ">Devolución con observaciones</span>';
                break;
            default:
                echo '<span class="badge badge-serie">Desconocido</span>';
        }
        ?>
    </td>
</tr>

<!-- FILA DETALLE -->
<tr class="detalle detalle-<?= $h['ID'] ?>">
    <td colspan="7">
        <strong>Detalle del préstamo #<?= $h['ID'] ?></strong>
        <br><br>

        <table style="width:95%;margin:auto;">
            <thead>
            <tr>
                <th>CLAVE</th>
                <th>SERIE</th>
                <th>Nota Entrega</th>
                <th>Nota Devolución</th>
                <th>F. Devolución</th>
                <th>H. Devolución</th>
            </tr>
            </thead>

            <tbody>
            <?php foreach ($detalles[$h['ID']] as $d): ?>
                <tr>
                    <td><?= htmlspecialchars($d['CLAVE_PRODUCTO']) ?></td>
                    <td><span class="badge badge-serie"><?= htmlspecialchars($d['SERIE']) ?></span></td>
                    <td><?= htmlspecialchars($d['NOTA_ENTREGA']) ?></td>
                    <td><?= htmlspecialchars($d['NOTA_DEVOLUCION']) ?></td>
                    <td><?= htmlspecialchars($d['FECHA_DEVOLUCION']) ?></td>
                    <td><?= htmlspecialchars($d['HORA_DEVOLUCION']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

    </td>
</tr>

<?php endforeach; ?>
</tbody>

</table>
</div>

<script>
// Expandir / Ocultar detalle
document.querySelectorAll(".fila-click").forEach(fila => {
    fila.addEventListener("click", () => {
        let id = fila.getAttribute("data-id");
        let det = document.querySelector(".detalle-" + id);

        det.style.display = det.style.display === "table-row" ? "none" : "table-row";
    });
});
</script>

</body>
</html>
