<?php
// views/pages/raspadita/resumen_ventas_pagos.php
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

if (!isset($_SESSION['idusuario'], $_SESSION['usuario'])) {
  header("Location: ../raspadita/login.php"); exit;
}

require_once __DIR__ . '/../conex.php';
$db = $conn ?? null;
if (!$db instanceof mysqli) { http_response_code(500); die("Sin conexión BD"); }
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

$idusuario = (int)$_SESSION['idusuario'];
$usuario   = htmlspecialchars((string)$_SESSION['usuario'], ENT_QUOTES, 'UTF-8');

// Permiso raspadita
$raspPerm = 0;
$stmt = mysqli_prepare($db, "SELECT COALESCE(raspadita,0) raspadita FROM tbr_usuario WHERE idusuario=? LIMIT 1");
mysqli_stmt_bind_param($stmt, "i", $idusuario);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($res)) $raspPerm = (int)$row['raspadita'];
mysqli_stmt_close($stmt);
if ($raspPerm !== 1) { http_response_code(403); die("Acceso denegado"); }

// Activo menú
$active = 'resumen';
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Resumen Ventas & Pagos · Raspaditas</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

  <style>
    body{background:#f4f6f9;}
    .sidebar{width:150px;background:#343a40;padding:20px;height:100vh;position:fixed;left:0;top:0;display:flex;flex-direction:column;align-items:center;}
    .sidebar a{color:#fff;text-decoration:none;padding:10px 15px;display:block;width:100%;text-align:center;}
    .sidebar a:hover{background:#495057;border-radius:8px;}
    .sidebar .active{font-weight:bold;color:#17a2b8;}
    .main-content{margin-left:0;transition:margin-left .3s;}
    @media(min-width:769px){.main-content{margin-left:150px;}}
    .badge-soft{background:rgba(23,162,184,.15);color:#0b7285;border:1px solid rgba(23,162,184,.35);}
    .card{border-radius:14px;}
    .kpi-card{border-radius:14px;}
    .kpi-label{opacity:.85;font-size:.9rem;}
    .kpi-value{font-size:1.45rem;font-weight:800;}
  </style>
</head>
<body>

<!-- ✅ MISMO USO QUE coordinador.php -->
<nav class="sidebar" id="sidebar">
  <?php include __DIR__ . '/menu_raspadita.php'; ?>
</nav>

<div class="main-content p-2 p-md-3">

  <nav class="navbar navbar-light bg-light rounded-3 mb-3">
    <div class="container-fluid">
      <span class="navbar-brand">
        <i class="fa-solid fa-calculator"></i> Resumen Ventas & Pagos
      </span>
      <div class="ms-auto d-flex gap-2 align-items-center">
        <span class="badge badge-soft px-3 py-2"><i class="fa fa-user"></i> <?= $usuario ?></span>
        <span class="badge badge-soft px-3 py-2"><i class="fa fa-clock"></i> <span id="hora"></span></span>
      </div>
    </div>
  </nav>

  <!-- FILTROS -->
  <div class="card mb-3">
    <div class="card-body">

      <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
        <h6 class="mb-0"><i class="fa-solid fa-filter"></i> Filtros</h6>
        <div class="d-flex gap-2">
          <button class="btn btn-outline-primary" type="button" id="btnHoy">
            <i class="fa-solid fa-calendar-day"></i> Hoy
          </button>
          <button class="btn btn-primary" type="button" id="btnBuscar">
            <i class="fa-solid fa-magnifying-glass"></i> Buscar
          </button>
        </div>
      </div>

      <div class="row g-2 align-items-end">
        <div class="col-12 col-md-3">
          <label class="form-label fw-semibold">Fecha inicio</label>
          <input type="date" class="form-control" id="fi">
        </div>
        <div class="col-12 col-md-3">
          <label class="form-label fw-semibold">Fecha fin</label>
          <input type="date" class="form-control" id="ff">
        </div>
        <div class="col-12 col-md-6">
          <div class="alert alert-info mb-0 py-2">
            <i class="fa-solid fa-circle-info me-1"></i>
            Se suman: ventas, efectivo, crédito, abonos, descuentos y pagos (premios pagados) por rango de fechas.
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- KPI CARDS -->
  <div class="row g-3">

    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-cart-shopping text-primary me-2"></i>Ventas (Total)</div>
          <div class="kpi-value" id="kpiVentas">$0.00</div>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-money-bill-wave text-success me-2"></i>Efectivo</div>
          <div class="kpi-value" id="kpiEfectivo">$0.00</div>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-credit-card text-danger me-2"></i>Crédito</div>
          <div class="kpi-value" id="kpiCredito">$0.00</div>
        </div>
      </div>
    </div>

    <!-- ✅ ABONO -->
    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-hand-holding-dollar text-info me-2"></i>Abonos</div>
          <div class="kpi-value" id="kpiAbono">$0.00</div>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-tags text-warning me-2"></i>Descuentos (Total)</div>
          <div class="kpi-value" id="kpiDescuentos">$0.00</div>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4">
      <div class="card kpi-card">
        <div class="card-body">
          <div class="kpi-label"><i class="fa-solid fa-gift text-secondary me-2"></i>Pagos / Premios pagados</div>
          <div class="kpi-value" id="kpiPagos">$0.00</div>
        </div>
      </div>
    </div>

  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
  // Hora EC
  (function(){
    function pad2(n){return String(n).padStart(2,'0');}
    function tick(){
      const now = new Date();
      const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
      const el = document.getElementById('hora');
      if (el) el.textContent = pad2(ec.getHours())+":"+pad2(ec.getMinutes());
    }
    tick(); setInterval(tick, 30000);
  })();

  const $ = (id) => document.getElementById(id);

  function hoyISO(){
    const d = new Date();
    const mm = String(d.getMonth()+1).padStart(2,'0');
    const dd = String(d.getDate()).padStart(2,'0');
    return `${d.getFullYear()}-${mm}-${dd}`;
  }

  const money = (n) => {
    const x = Number(n || 0);
    return x.toLocaleString('es-EC', { style:'currency', currency:'USD' });
  };

  async function postJson(url, payload){
    const r = await fetch(url, {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify(payload || {})
    });

    const txt = await r.text();
    let data = null;
    try { data = JSON.parse(txt); } catch(e){}

    if(!r.ok){
      console.error('HTTP', r.status, txt);
      throw new Error((data && (data.message||data.detail)) ? (data.message||data.detail) : ('Error HTTP ' + r.status));
    }
    if(!data || data.success !== true){
      console.error('NOT SUCCESS', txt);
      throw new Error((data && (data.message||data.detail)) ? (data.message||data.detail) : 'La API no devolvió success=true');
    }
    return data;
  }

  async function cargar(){
    const fi = $('fi').value || hoyISO();
    const ff = $('ff').value || hoyISO();

    const data = await postJson('api/resumen_ventas_pagos.php', {
      fecha_inicio: fi,
      fecha_fin: ff
    });

    $('kpiVentas').textContent     = money(data.ventas_total);
    $('kpiEfectivo').textContent   = money(data.ventas_efectivo);
    $('kpiCredito').textContent    = money(data.ventas_credito);
    $('kpiAbono').textContent      = money(data.ventas_abono);
    $('kpiDescuentos').textContent = money(data.descuentos_total);
    $('kpiPagos').textContent      = money(data.pagos_total);
  }

  $('btnBuscar').addEventListener('click', () => {
    cargar().catch(e => Swal.fire('Error', e.message || 'Error', 'error'));
  });

  $('btnHoy').addEventListener('click', () => {
    const h = hoyISO();
    $('fi').value = h;
    $('ff').value = h;
    cargar().catch(e => Swal.fire('Error', e.message || 'Error', 'error'));
  });

  document.addEventListener('DOMContentLoaded', () => {
    const h = hoyISO();
    $('fi').value = h;
    $('ff').value = h;
    cargar().catch(e => Swal.fire('Error', e.message || 'Error', 'error'));
  });
</script>

</body>
</html>