<?php
$servername = "localhost";
$username = "lotto";
$password = "12Qwaszx**";
$dbname = "lotto";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Error de conexión: " . $conn->connect_error);
}

$dayOption = $_POST['table'] ?? '';
$month = $_POST['month'] ?? '';
$dayNumber = $_POST['day'] ?? '';
$year = $_POST['year'] ?? '';

$where = ["1=1"];

if ($dayOption === "smartes") {
    $where[] = "dia = 'Martes'";
} elseif ($dayOption === "ssabado") {
    $where[] = "dia = 'Sábado'";
} elseif ($dayOption === "sabado_martes") {
    $where[] = "(dia = 'Martes' OR dia = 'Sábado')";
}
if (!empty($month)) {
    $monthClean = $conn->real_escape_string($month);
    $where[] = "LOWER(mes) = LOWER('$monthClean')";
}
if (!empty($year)) {
    $yearInt = intval($year);
    $where[] = "año = $yearInt";
}
if (!empty($dayNumber)) {
    $dayInt = intval($dayNumber);
    $where[] = "DAY(fecha) = $dayInt";
}

$whereSql = implode(" AND ", $where);
$sql = "SELECT pega3 FROM sorteo WHERE $whereSql";
$result = $conn->query($sql);

$frequencies = [];

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $num = intval($row['pega3']);
        if ($num !== null) {
            $frequencies[$num] = ($frequencies[$num] ?? 0) + 1;
        }
    }

    arsort($frequencies);

    $maxNumber = 999;
    $jugados = [];
    $no_jugados = [];
    for ($i = 0; $i <= $maxNumber; $i++) {
        if (isset($frequencies[$i]) && $frequencies[$i] > 0) {
            $jugados[$i] = $frequencies[$i];
        } else {
            $no_jugados[] = $i;
        }
    }

    $groups = ['3+' => [], '2' => [], '1' => []];
    foreach ($jugados as $num => $count) {
        if ($count >= 3) $groups['3+'][$num] = $count;
        else if ($count == 2) $groups['2'][$num] = $count;
        else $groups['1'][$num] = $count;
    }

    // Agrupar no jugados por centenas
    $centenas = [];
    foreach ($no_jugados as $num) {
        $grupo = floor($num / 100) * 100;
        $centenas[$grupo][] = str_pad($num, 3, '0', STR_PAD_LEFT);
    }
    ksort($centenas);

} else {
    echo "<div style='padding:20px; color:#555;'>No se encontraron resultados.</div>";
    exit;
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Resultados Pega3</title>
  <style>
    body {
      font-family: 'Segoe UI', sans-serif;
      background: #f4f6f9;
      padding: 20px;
    }
    h2 {
      color: #007bff;
    }
    .group-title {
      font-weight: 700;
      font-size: 1.2rem;
      margin-top: 30px;
      margin-bottom: 15px;
      border-bottom: 2px solid;
      padding-bottom: 5px;
    }
    .group-title.strong { border-color: #28a745; color: #28a745; }
    .group-title.medium { border-color: #ffc107; color: #b38f00; }
    .group-title.light { border-color: #6c757d; color: #6c757d; }

    .cards {
      display: grid;
      grid-template-columns: repeat(auto-fill,minmax(110px,1fr));
      gap: 12px;
    }
    .card {
      background: #e9ecef;
      border-radius: 8px;
      padding: 10px;
      box-shadow: 0 1px 4px rgb(0 0 0 / 0.1);
      text-align: center;
    }
    .card .number {
      font-size: 1.5rem;
      font-weight: 700;
    }
    .card .count {
      font-size: 1rem;
      color: #444;
    }
    .count.strong { color: #28a745; font-weight: 700; }
    .count.medium { color: #b38f00; font-weight: 600; }
    .count.light { color: #6c757d; font-weight: 600; }

    .accordion-block {
      margin-bottom: 15px;
      border-radius: 8px;
      overflow: hidden;
      background: white;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }

    .accordion-header {
      background-color: #007bff;
      color: white;
      font-size: 1rem;
      font-weight: bold;
      padding: 14px 20px;
      width: 100%;
      text-align: left;
      border: none;
      cursor: pointer;
      outline: none;
    }

    .accordion-header:hover {
      background-color: #0056b3;
    }

    .accordion-content {
      display: none;
      padding: 0 20px 20px;
      animation: fadein 0.3s;
    }

    @keyframes fadein {
      from {opacity: 0;}
      to {opacity: 1;}
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      background: white;
    }

    thead {
      background-color: #007bff;
      color: white;
    }

    thead th {
      padding: 10px;
      text-align: center;
    }

    tbody {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 6px 16px;
    }

    tbody tr {
      display: contents;
    }

    tbody td {
      padding: 8px;
      text-align: center;
      font-size: 1rem;
      color: #333;
      border-left: 3px solid transparent;
    }

    tbody td:hover {
      border-left-color: #007bff;
      font-weight: bold;
    }

    @media(max-width:800px) {
      tbody {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  </style>
</head>
<body>

<h2>Resultados de Números Jugados</h2>

<?php if(count($groups['3+']) > 0): ?>
  <div class="group-title strong">Frecuencia 3 o más</div>
  <div class="cards">
    <?php foreach($groups['3+'] as $num => $count): ?>
      <div class="card">
        <div class="number"><?= str_pad($num,3,'0',STR_PAD_LEFT) ?></div>
        <div class="count strong"><?= $count ?></div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<?php if(count($groups['2']) > 0): ?>
  <div class="group-title medium">Frecuencia 2</div>
  <div class="cards">
    <?php foreach($groups['2'] as $num => $count): ?>
      <div class="card">
        <div class="number"><?= str_pad($num,3,'0',STR_PAD_LEFT) ?></div>
        <div class="count medium"><?= $count ?></div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<?php if(count($groups['1']) > 0): ?>
  <div class="group-title light">Frecuencia 1</div>
  <div class="cards">
    <?php foreach($groups['1'] as $num => $count): ?>
      <div class="card">
        <div class="number"><?= str_pad($num,3,'0',STR_PAD_LEFT) ?></div>
        <div class="count light"><?= $count ?></div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<h2 style="margin-top:40px;">Números No Jugados por Centena</h2>

<?php foreach ($centenas as $inicio => $lista): ?>
  <div class="accordion-block">
    <button class="accordion-header" onclick="toggleAccordion(this)">
      Centena <?= str_pad($inicio,3,'0',STR_PAD_LEFT) ?>–<?= str_pad($inicio+99,3,'0',STR_PAD_LEFT) ?>
    </button>
    <div class="accordion-content">
      <table>
        <thead><tr><th>Números</th></tr></thead>
        <tbody>
          <?php foreach ($lista as $num): ?>
            <tr><td><?= $num ?></td></tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
<?php endforeach; ?>

<script>
function toggleAccordion(button) {
  const content = button.nextElementSibling;
  const isOpen = content.style.display === "block";
  document.querySelectorAll('.accordion-content').forEach(el => el.style.display = 'none');
  if (!isOpen) content.style.display = "block";
}
</script>

</body>
</html>
