<?php
// Conexão com o banco
$pdo = new PDO("mysql:host=localhost;dbname=kaltekgo_avila;charset=utf8", "kaltekgo_admin", "kaltek@2024");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Verifica se não veio parâmetro ?semana= e redireciona para semana atual (0)
if (!isset($_GET['semana'])) {
    header("Location: ?semana=0");
    exit;
}

// Horários fixos
$horarios = [
    "07:05","07:55","08:45","10:00","10:50","11:40",
    "13:20","14:10","15:30","16:10","16:50","17:40"
];

// Dias da semana
$dias = ["Segunda","Terça","Quarta","Quinta","Sexta"];

// Determina a semana selecionada via GET
$semana_offset = isset($_GET['semana']) ? (int)$_GET['semana'] : 0; // 0 = semana atual
$hoje = strtotime('today');
$inicio_semana = strtotime("$semana_offset week monday", $hoje);

// Datas da semana
$datas = [];
for($i=0; $i<5; $i++){
    $datas[] = date('Y-m-d', strtotime("+$i day", $inicio_semana));
}

// Intervalo da semana
$data_inicio = date('d/m', $inicio_semana);
$data_fim = date('d/m', strtotime('+4 days', $inicio_semana));
$intervalo_semana = $data_inicio . " a " . $data_fim;

// Buscar reservas
$stmt = $pdo->query("SELECT horario, data_aula, descricao FROM reserva_maker");
$reservas_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Organizar reservas
$reservas = [];
foreach($reservas_raw as $r){
    $data = date('Y-m-d', strtotime($r['data_aula']));
    $reservas[$data][$r['horario']] = $r['descricao'];
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Agenda Semanal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style>
table { width:100%; text-align:center; border-collapse:collapse; background:#fff; box-shadow:0 0 10px rgba(0,0,0,0.1); text-transform:uppercase; min-width:700px; margin-top:-10px; }
th, td { padding:12px 15px; font-size:12px; border:1px solid #000 !important; vertical-align:middle !important; }
th { background-color:#000; color:#fff; }
tr:nth-child(even) { background-color:#f4f4f4; }
tr:hover { background-color:#e0e0e0; }
h2 { margin-top:20px; margin-bottom:5px; }
h4.subtitulo { margin-bottom:20px; font-weight:normal; color:#555; }
.btn-voltar { margin:-15px auto; display:block; width:200px; }
.bg-success { cursor:pointer; }
.data-pequena { display:block; font-size:10px; font-weight:normal; margin-top:2px; }
.semana-btns { margin-bottom:20px; }
</style>
</head>
<body>
<div class="container">
<h2 class="text-center">Agenda da Sala Maker</h2>

<div class="text-center semana-btns">
    <a href="?semana=<?= $semana_offset-1 ?>" class="btn btn-default">Semana Anterior</a>
    <span style="margin:0 15px;">Semana: <?= $intervalo_semana ?></span>
    <a href="?semana=<?= $semana_offset+1 ?>" class="btn btn-default">Próxima Semana</a>
</div>

<table class="table table-bordered">
    <thead>
        <tr>
            <th class="text-center">Horário</th>
            <?php foreach($dias as $index => $dia): 
                $dataFormatada = date("d/m/Y", strtotime($datas[$index]));
            ?>
                <th class="text-center">
                    <?= $dia ?>
                    <span class="data-pequena">(<?= $dataFormatada ?>)</span>
                </th>
            <?php endforeach; ?>
        </tr>
    </thead>
    <tbody>
    <?php foreach($horarios as $horario): ?>
        <tr>
            <td class="text-center"><?= $horario ?></td>
<?php foreach($datas as $data): 
    $descricaoOriginal = $reservas[$data][$horario] ?? 'Disponível';  

    if ($descricaoOriginal === 'Disponível') {
        $classe = 'bg-success reserva-cell text-uppercase'; // Verde quando livre
        $descricao = $descricaoOriginal;
    } else {
        $classe = 'bg-danger'; // Vermelho quando reservado
        // Limita a exibição a 20 caracteres + "..."
        $descricao = mb_strlen($descricaoOriginal) > 20 
            ? mb_substr($descricaoOriginal, 0, 20) . "..."
            : $descricaoOriginal;
    }
?>
<td class="text-center  <?= $classe ?>" 
    title="<?= htmlspecialchars($descricaoOriginal) ?>" 
    <?php if($descricaoOriginal==='Disponível'): ?>
        data-horario="<?= $horario ?>" data-data="<?= $data ?>"
    <?php endif; ?>>
    <?= htmlspecialchars($descricao) ?>
</td>
<?php endforeach; ?>

        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<a href="reservaEspecifica.php" class="btn btn-primary btn-voltar text-center">Reserva de data específica</a>
</div>

<!-- Modal -->
<div id="mainModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="formReserva">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title" id="mainModalTitle"></h4>
        </div>
        <div class="modal-body">
          <div id="alertContent" class="text-center" style="display:none;">
            <p id="alertMessage"></p>
          </div>
          <div id="formContent">
            <div class="form-group">
              <label>Horário</label>
              <input type="text" class="form-control" name="horario" id="modal-horario" readonly>
            </div>
            <div class="form-group">
              <label>Data</label>
              <input type="text" class="form-control" id="modal-data" readonly>
              <input type="hidden" name="data_aula" id="modal-data-hidden">
            </div>
            <div class="form-group">
              <label>Descrição</label>
              <input type="text" class="form-control text-uppercase" name="descricao" required maxlength="20">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" id="btnReservar" class="btn btn-primary">Reservar</button>
          <button type="button" class="btn btn-success" id="btnOk" data-dismiss="modal" style="display:none;">OK</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
$(function(){
    function formatDateBR(dateStr){
        let d = new Date(dateStr);
        let dia = String(d.getDate()).padStart(2,'0');
        let mes = String(d.getMonth()+1).padStart(2,'0');
        let ano = d.getFullYear();
        return `${dia}/${mes}/${ano}`;
    }

    $(".reserva-cell").on("click", function(){
        $("#mainModalTitle").text("Nova Reserva");
        $("#formContent").show();
        $("#btnReservar").show();
        $("#alertContent").hide();
        $("#btnOk").hide();

        let horario = $(this).data("horario");
        let data = $(this).data("data");

        $("#modal-horario").val(horario);
        $("#modal-data").val(formatDateBR(data));
        $("#modal-data-hidden").val(data);

        $("#mainModal").modal("show");
    });

    $("#formReserva").on("submit", function(e){
        e.preventDefault();
        $.post("salvar_.php", $(this).serialize(), function(resposta){
            $("#mainModalTitle").text("Mensagem");
            $("#formContent").hide();
            $("#btnReservar").hide();
            $("#alertContent").show();
            $("#btnOk").show();
            $("#alertMessage").html(resposta);

            $("#btnOk").on("click", function(){
                location.reload();
            });
        });
    });
});
</script>
</body>
</html>
