<?php
require_once __DIR__ . '/../../includes/layout.php';

$pdo = getDBConnection();

// Filters handling
$filter_sucursal = isset($_GET['sucursal_id']) ? (int)$_GET['sucursal_id'] : 0;
$fecha_desde = $_GET['fecha_desde'] ?? date('Y-m-01');
$fecha_hasta = $_GET['fecha_hasta'] ?? date('Y-m-d');
$tipo_mov = $_GET['tipo_mov'] ?? 'todos';

// Fetch sucursales for filter dropdown
try {
    $stmtSuc = $pdo->query("SELECT id, nombre FROM sucursales ORDER BY nombre");
    $sucursales = $stmtSuc->fetchAll();
} catch (Exception $e) {
    $sucursales = [];
}

// Build query
$where = [];
$params = [];

if ($filter_sucursal > 0) {
    $where[] = "cm.sucursal_id = ?";
    $params[] = $filter_sucursal;
}

if (!empty($fecha_desde)) {
    $where[] = "cm.fecha >= ?";
    $params[] = $fecha_desde . " 00:00:00";
}

if (!empty($fecha_hasta)) {
    $where[] = "cm.fecha <= ?";
    $params[] = $fecha_hasta . " 23:59:59";
}

if ($tipo_mov !== 'todos') {
    $where[] = "cm.tipo = ?";
    $params[] = $tipo_mov;
}

$whereSql = "";
if (count($where) > 0) {
    $whereSql = "WHERE " . implode(" AND ", $where);
}

$sql = "SELECT cm.*, s.nombre as sucursal_nombre, u.usuario as usuario_nombre 
        FROM caja_chica_movimientos cm
        LEFT JOIN sucursales s ON s.id = cm.sucursal_id
        LEFT JOIN usuarios u ON u.id = cm.usuario_id
        $whereSql
        ORDER BY cm.fecha DESC, cm.id DESC";

try {
    $stmtMovs = $pdo->prepare($sql);
    $stmtMovs->execute($params);
    $movimientos = $stmtMovs->fetchAll();
} catch (Exception $e) {
    $movimientos = [];
    $error_msg = "Error al cargar movimientos: " . $e->getMessage();
}

// Calculate totals from filtered records
$totalIngresos = 0;
$totalEgresos = 0;
foreach ($movimientos as $m) {
    if ($m['tipo'] === 'ingreso') {
        $totalIngresos += (float)$m['monto'];
    } elseif ($m['tipo'] === 'egreso') {
        $totalEgresos += (float)$m['monto'];
    }
}
$balance = $totalIngresos - $totalEgresos;

renderHeader('Reporte Caja Chica', 'caja_chica');
?>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
.report-wrap {
    max-width: 1400px;
    margin: 0 auto;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}
.report-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
}
.report-header h1 {
    font-size: 1.75rem;
    font-weight: 800;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

/* Style filters panel to use elevated theme */
.filters-card {
    background: var(--surface-elevated);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.25rem 1.5rem;
}
.filters-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.25rem;
    align-items: end;
}
.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.35rem;
}
.filter-label {
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-secondary);
}
.filter-input {
    width: 100%;
    padding: 0.6rem 0.85rem;
    border-radius: var(--radius-sm);
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text-primary);
    font-size: 0.875rem;
    outline: none;
    transition: border-color var(--transition), box-shadow var(--transition);
    box-sizing: border-box;
}
.filter-input:focus {
    border-color: var(--accent-color);
    box-shadow: var(--focus-ring);
}
.btn-filter {
    padding: 0.65rem 1.25rem;
    background: var(--accent-color);
    color: var(--primary);
    border: none;
    border-radius: var(--radius-sm);
    font-weight: 700;
    font-size: 0.875rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all var(--transition);
    height: 38px;
}
.btn-filter:hover {
    opacity: 0.9;
    transform: translateY(-1px);
}

/* KPI cards */
.kpis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 1.5rem;
}
.kpi-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.5rem;
    position: relative;
    overflow: hidden;
}
.kpi-card-icon {
    position: absolute;
    right: 1.25rem;
    top: 1.25rem;
    font-size: 2rem;
    opacity: 0.15;
}
.kpi-card-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    font-weight: 700;
    color: var(--text-secondary);
    letter-spacing: 0.05em;
}
.kpi-card-value {
    font-size: 2.25rem;
    font-weight: 800;
    margin-top: 0.5rem;
}

/* Badges for movement types */
.badge-ingreso {
    background: rgba(34, 197, 94, 0.12);
    color: var(--success);
    border: 1px solid rgba(34, 197, 94, 0.25);
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.5rem;
    border-radius: 6px;
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
}
.badge-egreso {
    background: rgba(239, 68, 68, 0.12);
    color: var(--danger);
    border: 1px solid rgba(239, 68, 68, 0.25);
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.5rem;
    border-radius: 6px;
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
}
</style>

<div class="report-wrap">
    <div class="report-header">
        <h1><i class="bi bi-wallet2" style="color: var(--accent-color);"></i> Reporte de Caja Chica</h1>
    </div>

    <?php if (isset($error_msg)): ?>
        <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2); color: var(--danger); padding: 1rem; border-radius: var(--radius); font-weight: 600;">
            <?= htmlspecialchars($error_msg) ?>
        </div>
    <?php endif; ?>

    <!-- Filters Panel -->
    <div class="filters-card">
        <form method="GET" action="modules/finanzas/caja_chica.php">
            <div class="filters-grid">
                <div class="filter-group">
                    <label class="filter-label">Sucursal</label>
                    <select name="sucursal_id" class="filter-input">
                        <option value="0">🌐 Todas las sucursales</option>
                        <?php foreach ($sucursales as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= $filter_sucursal == $s['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars(preg_replace('/^\([^)]*\)\s*/', '', $s['nombre'])) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Desde</label>
                    <input type="date" name="fecha_desde" class="filter-input" value="<?= htmlspecialchars($fecha_desde) ?>">
                </div>
                <div class="filter-group">
                    <label class="filter-label">Hasta</label>
                    <input type="date" name="fecha_hasta" class="filter-input" value="<?= htmlspecialchars($fecha_hasta) ?>">
                </div>
                <div class="filter-group">
                    <label class="filter-label">Tipo Movimiento</label>
                    <select name="tipo_mov" class="filter-input">
                        <option value="todos" <?= $tipo_mov === 'todos' ? 'selected' : '' ?>>Todos</option>
                        <option value="ingreso" <?= $tipo_mov === 'ingreso' ? 'selected' : '' ?>>Ingreso</option>
                        <option value="egreso" <?= $tipo_mov === 'egreso' ? 'selected' : '' ?>>Egreso</option>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn-filter">
                        <i class="bi bi-search"></i> Buscar
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- KPIs -->
    <div class="kpis-grid">
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-arrow-down-left-circle" style="color: var(--success);"></i></div>
            <div class="kpi-card-label">Total Ingresos</div>
            <div class="kpi-card-value" style="color: var(--success);">Q<?= number_format($totalIngresos, 2) ?></div>
        </div>
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-arrow-up-right-circle" style="color: var(--danger);"></i></div>
            <div class="kpi-card-label">Total Egresos</div>
            <div class="kpi-card-value" style="color: var(--danger);">Q<?= number_format($totalEgresos, 2) ?></div>
        </div>
        <div class="kpi-card" style="border-color: <?= $balance >= 0 ? 'rgba(34, 197, 94, 0.3)' : 'rgba(239, 68, 68, 0.3)' ?>;">
            <div class="kpi-card-icon"><i class="bi bi-piggy-bank" style="color: <?= $balance >= 0 ? 'var(--success)' : 'var(--danger)' ?>;"></i></div>
            <div class="kpi-card-label">Balance Neto</div>
            <div class="kpi-card-value" style="color: <?= $balance >= 0 ? 'var(--success)' : 'var(--danger)' ?>;">Q<?= number_format($balance, 2) ?></div>
        </div>
    </div>

    <!-- Table -->
    <div class="table-wrapper">
        <table class="table-premium">
            <thead>
                <tr>
                    <th>Fecha y Hora</th>
                    <th>Sucursal</th>
                    <th>Usuario</th>
                    <th>Tipo</th>
                    <th>Concepto</th>
                    <th style="text-align: right;">Monto</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($movimientos)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 3rem; color: var(--text-muted);">
                            <i class="bi bi-info-circle" style="font-size: 1.5rem; display: block; margin-bottom: 0.5rem;"></i>
                            No se encontraron movimientos para los filtros seleccionados.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($movimientos as $m): ?>
                        <tr>
                            <td style="white-space: nowrap; font-weight: 500;">
                                <?= date('d/m/Y H:i', strtotime($m['fecha'])) ?>
                            </td>
                            <td>
                                <?= htmlspecialchars(preg_replace('/^\([^)]*\)\s*/', '', $m['sucursal_nombre'] ?? 'Desconocida')) ?>
                            </td>
                            <td>
                                <?= htmlspecialchars($m['usuario_nombre'] ?? 'Sistema') ?>
                            </td>
                            <td>
                                <span class="badge-<?= $m['tipo'] ?>">
                                    <?= $m['tipo'] === 'ingreso' ? 'Ingreso' : 'Egreso' ?>
                                </span>
                            </td>
                            <td style="max-width: 400px; overflow: hidden; text-overflow: ellipsis;">
                                <?= htmlspecialchars($m['concepto']) ?>
                            </td>
                            <td style="text-align: right; font-weight: 700; color: <?= $m['tipo'] === 'ingreso' ? 'var(--success)' : 'var(--text-primary)' ?>;">
                                Q<?= number_format($m['monto'], 2) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php renderFooter(); ?>
