<?php
// views/pages/raspadita/reporte.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"); }

// CSRF
if (!isset($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = (string)$_SESSION['csrf'];
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Reporte · 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.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">

  <!-- Buttons -->
  <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">

  <!-- Select2 -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.5.2/dist/select2-bootstrap4.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{border-radius:14px;}
    .kpi .num{font-size:1.2rem;font-weight:800;}
    .kpi .sub{font-size:12px;color:#6c757d;}
    .table-sm th,.table-sm td{padding:.45rem .5rem;}
  </style>
</head>
<body>

<nav class="sidebar" id="sidebar">
  <?php $active='reporte'; 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-chart-column"></i> Reporte Financiero</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>

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

      <div class="row g-2 align-items-end">
        <div class="col-6 col-md-2">
          <label class="form-label fw-semibold">Desde</label>
          <input type="date" id="fIni" class="form-control">
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label fw-semibold">Hasta</label>
          <input type="date" id="fFin" class="form-control">
        </div>

        <div class="col-12 col-md-3">
          <label class="form-label fw-semibold">Punto de venta</label>
          <select id="selPunto" class="form-select"></select>
        </div>

        <div class="col-12 col-md-4">
          <label class="form-label fw-semibold">Canillita</label>
          <select id="selCan" class="form-select"></select>
        </div>

        <div class="col-12 col-md-1 d-grid">
          <button class="btn btn-dark" type="button" onclick="cargarReporte()">
            <i class="fa-solid fa-magnifying-glass"></i>
          </button>
        </div>
      </div>

      <hr class="my-3">

      <!-- KPIs (se mantienen) -->
      <div class="row g-2">
        <div class="col-6 col-md-1">
          <div class="alert alert-primary kpi mb-0">
            <div class="sub">Asignadas</div>
            <div class="num" id="kAsi">0</div>
          </div>
        </div>        

        <div class="col-6 col-md-1">
          <div class="alert alert-info kpi mb-0">
            <div class="sub">Entregadas</div>
            <div class="num" id="kEnt">0</div>
          </div>
        </div>

        <div class="col-6 col-md-1">
          <div class="alert alert-success kpi mb-0">
            <div class="sub">Vendidas</div>
            <div class="num" id="kVen">0</div>
          </div>
        </div>
		
		<div class="col-6 col-md-1">
          <div class="alert alert-secondary kpi mb-0">
            <div class="sub">Valor asignado</div>
            <div class="num" id="kVA">$0.00</div>
          </div>
        </div>
		
		<div class="col-6 col-md-1">
          <div class="alert alert-secondary kpi mb-0">
            <div class="sub">Valor entregado</div>
            <div class="num" id="kVE">$0.00</div>
          </div>
        </div>

        <div class="col-6 col-md-1">
          <div class="alert alert-dark kpi mb-0">
            <div class="sub">Valor vendido</div>
            <div class="num" id="kVV">$0.00</div>
          </div>
        </div>

        <div class="col-6 col-md-1">
          <div class="alert alert-warning kpi mb-0">
            <div class="sub">Premios pagados</div>
            <div class="num" id="kPP">$0.00</div>
          </div>
        </div>

        <div class="col-12 col-md-1">
          <div class="alert alert-danger kpi mb-0">
            <div class="sub">Saldo</div>
            <div class="num" id="kSaldo">$0.00</div>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Resumen (SIN Asignadas / Valor asignado) -->
  <div class="card mb-3">
    <div class="card-body">
      <h6 class="mb-3"><i class="fa-solid fa-layer-group"></i> Resumen por responsable</h6>
      <div class="table-responsive">
        <table id="tbRes" class="table table-sm table-striped w-100">
          <thead>
            <tr>
              <th>#</th>
              <th>Responsable</th>
              <th class="text-end">Entregadas</th>
              <th class="text-end">Vendidas</th>
              <th class="text-end">Valor vendido</th>
              <th class="text-end">Premios pagados</th>
              <th class="text-end">Saldo</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Detalle export -->
  <div class="card">
    <div class="card-body">
      <h6 class="mb-3"><i class="fa-solid fa-table"></i> Detalle (Exportar Excel/PDF)</h6>
      <div class="table-responsive">
        <table id="tbDet" class="table table-sm table-striped w-100">
          <thead>
            <tr>
              <th>#</th>
              <th>Código</th>
              <th>Estado</th>
              <th>Responsable</th>
              <th>Pagado por</th>
              <th class="text-end">Valor</th>
              <th class="text-end">Premio</th>
              <th class="text-end">Saldo fila</th>
              <th>Fecha</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <small class="text-muted d-block mt-2">
        Exporta desde los botones arriba (Excel / PDF / Imprimir).
      </small>
    </div>
  </div>

</div>

<script>
  window.CSRF = <?= json_encode($csrf, JSON_UNESCAPED_UNICODE) ?>;
</script>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<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 src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>

<!-- Buttons -->
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

<!-- Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></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);
  })();

  function money(v){ const n = Number(v||0); return '$' + n.toFixed(2); }
  function esc(s){ return String(s ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m])); }

  async function postJson(url, payload){
    const r = await fetch(url, {
      method:'POST',
      credentials:'same-origin',
      headers:{ 'Content-Type':'application/json', 'X-CSRF-Token': (window.CSRF||'') },
      body: JSON.stringify(payload||{})
    });
    const txt = await r.text();
    let j=null; try{ j=JSON.parse(txt); }catch(e){}
    if(!j) throw new Error('Respuesta no JSON: ' + txt.slice(0,200));
    if(!r.ok) throw new Error(j.message || `HTTP ${r.status}`);
    if(j.success !== true) throw new Error(j.message || 'Error');
    return j;
  }

  async function loadSimpleSelect(url, selId, placeholder){
    const sel = document.getElementById(selId);
    if(!sel) return;
    sel.innerHTML = `<option value="0">${placeholder}</option>`;
    const r = await fetch(url, { cache:'no-store', credentials:'same-origin' });
    const j = await r.json().catch(()=>null);
    if(!j || j.success !== true) return;
    (j.data || j.results || []).forEach(it=>{
      const id = String(it.id ?? 0);
      const text = String(it.text ?? '');
      if(id && text){
        const opt = document.createElement('option');
        opt.value = id;
        opt.textContent = text;
        sel.appendChild(opt);
      }
    });
  }

  function initCanSelect2(){
    const $sel = $('#selCan');
    $sel.select2({
      theme: "bootstrap4",
      width: "100%",
      placeholder: "— Todos los canillitas —",
      allowClear: true,
      minimumInputLength: 1,
      ajax: {
        url: 'api/canillitas_select2.php',
        dataType: 'json',
        delay: 250,
        cache: false,
        data: (params)=>({ q: params.term || '', page: params.page || 1 }),
        processResults: (data, params)=>{
          params.page = params.page || 1;
          return { results: data?.results || [], pagination:{ more: !!data?.pagination?.more } };
        }
      }
    });
  }

  function setHoy(){
    const now = new Date();
    const ec  = new Date(now.toLocaleString("en-US",{timeZone:"America/Guayaquil"}));
    const y = ec.getFullYear(), m=String(ec.getMonth()+1).padStart(2,'0'), d=String(ec.getDate()).padStart(2,'0');
    const hoy = `${y}-${m}-${d}`;
    document.getElementById('fIni').value = hoy;
    document.getElementById('fFin').value = hoy;
  }

  let dtRes=null, dtDet=null;

  function initTables(){
    if(!dtRes){
      dtRes = $('#tbRes').DataTable({
        searching:true, lengthChange:false, pageLength:50, responsive:true, ordering:false,
        language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"},
        // ✅ ahora el resumen tiene 7 columnas: 0..6, numéricas desde 2..6
        columnDefs:[{targets:[2,3,4,5,6], className:'text-end'}]
      });
    }
    if(!dtDet){
      dtDet = $('#tbDet').DataTable({
        searching:true, lengthChange:false, pageLength:100, responsive:true, ordering:false,
        dom: 'Bfrtip',
        buttons: [
          { extend:'excelHtml5', title:'Reporte_Raspaditas', className:'btn btn-success btn-sm' },
          { extend:'pdfHtml5',   title:'Reporte_Raspaditas', className:'btn btn-danger btn-sm', orientation:'landscape', pageSize:'A4' },
          { extend:'print',      title:'Reporte Raspaditas', className:'btn btn-dark btn-sm' }
        ],
        language:{url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json"},
        columnDefs:[{targets:[5,6,7], className:'text-end'}]
      });
    }
  }

  async function cargarReporte(){
    try{
      initTables();

      const fecha_ini = (document.getElementById('fIni').value || '').trim();
      const fecha_fin = (document.getElementById('fFin').value || '').trim();

      const id_punto = parseInt(document.getElementById('selPunto').value || '0', 10) || 0;
      const canVal = ($('#selCan').val() || '').toString();
      const id_canillita = parseInt(canVal || '0', 10) || 0;

      const j = await postJson('api/raspadita_reporte_financiero.php', {
        fecha_ini, fecha_fin, id_punto, id_canillita
      });

      const t = j.totales || {};
      document.getElementById('kAsi').textContent   = String(t.asignadas || 0);
      document.getElementById('kVA').textContent    = money(t.valor_asignado || 0);
      document.getElementById('kEnt').textContent   = String(t.entregadas || 0);
      document.getElementById('kVen').textContent   = String(t.vendidas || 0);
      document.getElementById('kVE').textContent    = money(t.valor_entregado || 0);
      document.getElementById('kVV').textContent    = money(t.valor_vendido || 0);
      document.getElementById('kPP').textContent    = money(t.premios_pagados || 0);
      document.getElementById('kSaldo').textContent = money(t.saldo || 0);

      // ✅ RESUMEN sin asignadas / valor asignado
      dtRes.clear();
      (j.resumen || []).forEach((r, idx)=>{
        dtRes.row.add([
          idx+1,
          `<b>${esc(r.responsable||'')}</b>`,
          r.entregadas||0,
          r.vendidas||0,
          money(r.valor_vendido||0),
          money(r.premios_pagados||0),
          money(r.saldo||0)
        ]);
      });
      dtRes.draw(false);

      dtDet.clear();
      (j.data || []).forEach((r, idx)=>{
        dtDet.row.add([
          idx+1,
          `<b>${esc(r.codigo||'')}</b>`,
          esc(r.estado||''),
          esc(r.responsable||''),
          esc(r.pagado_por||''),
          money(r.valor||0),
          money(r.premio||0),
          money(r.saldo_fila||0),
          esc(r.fecha_hora||'')
        ]);
      });
      dtDet.draw(false);

    }catch(e){
      console.error(e);
      Swal.fire('Error', e.message || 'No se pudo cargar', 'error');
    }
  }

  document.addEventListener('DOMContentLoaded', async ()=>{
    setHoy();
    initCanSelect2();
    await loadSimpleSelect('api/punto_venta_list.php', 'selPunto', '— Todos los puntos —');
    setTimeout(()=>cargarReporte(), 150);
  });
</script>

</body>
</html>