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

/* =======================
   CONFIG
======================= */
$table_name = "codes";   // NOVA TABELA
$page = "main.php";     // ajuste se seu arquivo tiver outro nome

$user_logado = $_SESSION['name'];
$role_logada = $_SESSION['role'];

/* =======================
   FUNÇÕES AUXILIARES
======================= */
function normalize_code($code) {
    $code = trim($code);
    // remove espaços duplicados
    $code = preg_replace('/\s+/', ' ', $code);
    return $code;
}

function validate_date_ymd($date) {
    // Espera YYYY-MM-DD (input type="date" já manda assim)
    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt && $dt->format('Y-m-d') === $date;
}

/* =======================
   LOAD DATA (ROLE SAFE)
======================= */
if ($role_logada === 'master') {
    $res = $db->select($table_name, '*');
} else {
    $res = $db->select(
        $table_name,
        '*',
        'owner = :owner',
        '',
        [':owner' => $user_logado]
    );
}

/* =======================
   UPDATE (SECURE)
======================= */
if (isset($_GET['update'])) {
    $idUpdate = (int)$_GET['update'];

    $resU = $db->select(
        $table_name,
        '*',
        'id = :id',
        '',
        [':id' => $idUpdate]
    );

    if (!$resU) {
        header("Location: $page?error=notfound");
        exit;
    }

    if ($role_logada !== 'master' && $resU[0]['owner'] !== $user_logado) {
        header("Location: $page?error=denied");
        exit;
    }
}

if (isset($_POST['submitU'])) {
    unset($_POST['submitU']);

    $idUpdate = (int)$_GET['update'];

    $code = normalize_code($_POST['code'] ?? '');
    $expires_at = $_POST['expires_at'] ?? '';

    if ($code === '' || !validate_date_ymd($expires_at)) {
        header("Location: $page?update=$idUpdate&error=invalid");
        exit;
    }

    // WHITELIST DOS CAMPOS
    $data = [
        'code' => $code,
        'expires_at' => $expires_at,
    ];

    $db->update(
        $table_name,
        $data,
        'id = :id',
        [':id' => $idUpdate]
    );

    header("Location: $page?status=updated");
    exit;
}

/* =======================
   CREATE (SEM DESCONTO DE CRÉDITOS)
======================= */
if (isset($_POST['submit'])) {
    unset($_POST['submit']);

    $code = normalize_code($_POST['code'] ?? '');
    $expires_at = $_POST['expires_at'] ?? '';

    if ($code === '' || !validate_date_ymd($expires_at)) {
        header("Location: $page?create=1&error=invalid");
        exit;
    }

    // WHITELIST DOS CAMPOS + owner
    $data = [
        'code' => $code,
        'expires_at' => $expires_at,
        'owner' => $user_logado
    ];

    // Insere no banco
    $db->insert($table_name, $data);

    header("Location: $page?status=created");
    exit;
}

/* =======================
   DELETE (SECURE)
======================= */
if (isset($_GET['delete'])) {
    $idDelete = (int)$_GET['delete'];

    $check = $db->select(
        $table_name,
        'owner',
        'id = :id',
        '',
        [':id' => $idDelete]
    );

    if (!$check) {
        header("Location: $page?error=notfound");
        exit;
    }

    if ($role_logada === 'master' || $check[0]['owner'] === $user_logado) {
        $db->delete(
            $table_name,
            'id = :id',
            [':id' => $idDelete]
        );
        header("Location: $page?status=deleted");
        exit;
    }

    header("Location: $page?error=denied");
    exit;
}
?>

<!-- CONFIRM DELETE MODAL -->
<div class="modal fade" id="confirm-delete">
    <div class="modal-dialog">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header">
                <h5>Confirmar exclusão</h5>
            </div>
            <div class="modal-body">
                Tem certeza que deseja excluir?
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<?php if (isset($_GET['create'])): ?>

<div class="col-md-12 mx-auto ctmain-table">
    <div class="card ctcard">
        <div class="card-header text-center">
            <h3>Adicionar Código</h3>
        </div>
        <div class="card-body">

            <?php if (isset($_GET['error']) && $_GET['error'] === 'invalid'): ?>
                <div class="alert alert-danger">Dados inválidos. Verifique o código e a data de expiração.</div>
            <?php endif; ?>

            <form method="post">
                <div class="form-group">
                    <label>Código</label>
                    <input class="form-control" name="code" required>
                </div>

                <div class="form-group">
                    <label>Data de expiração</label>
                    <input class="form-control" type="date" name="expires_at" required>
                </div>

                <button class="btn btn-info" name="submit">Criar</button>
            </form>
        </div>
    </div>
</div>

<?php elseif (isset($_GET['update'])): ?>

<div class="col-md-12 mx-auto ctmain-table">
    <div class="card ctcard">
        <div class="card-header text-center">
            <h3>Editar Código</h3>
        </div>
        <div class="card-body">

            <?php if (isset($_GET['error']) && $_GET['error'] === 'invalid'): ?>
                <div class="alert alert-danger">Dados inválidos. Verifique o código e a data de expiração.</div>
            <?php endif; ?>

            <form method="post">
                <div class="form-group">
                    <label>Código</label>
                    <input class="form-control" name="code" value="<?=$resU[0]['code']?>" required>
                </div>

                <div class="form-group">
                    <label>Data de expiração</label>
                    <input class="form-control" type="date" name="expires_at" value="<?=$resU[0]['expires_at']?>" required>
                </div>

                <button class="btn btn-info" name="submitU">Atualizar</button>
            </form>
        </div>
    </div>
</div>

<?php else: ?>

<div class="col-md-12 mx-auto ctmain-table">
    <div class="card ctcard">
        <div class="card-header text-center">
            <h3>Lista de Códigos</h3>
        </div>
        <div class="card-body">
            <a href="<?=$page?>?create=1" class="btn btn-info mb-3">Novo Código</a>

            <table class="table table-dark table-striped">
                <thead>
                    <tr>
                        <th>Código</th>
                        <th>Expiração</th>
                        <th>Status</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($res as $row): ?>
                    <?php
                        $status = "Ativo";
                        if (!empty($row['expires_at'])) {
                            $exp = DateTime::createFromFormat('Y-m-d', $row['expires_at']);
                            $today = new DateTime('today');
                            if ($exp && $exp < $today) $status = "Expirado";
                        }
                    ?>
                    <tr>
                        <td><?=$row['code']?></td>
                        <td>
                            <?php
                                if (!empty($row['expires_at'])) {
                                    $exp = DateTime::createFromFormat('Y-m-d', $row['expires_at']);
                                    echo $exp ? $exp->format('d/m/Y') : $row['expires_at'];
                                }
                            ?>
                        </td>
                        <td><?=$status?></td>
                        <td>
                            <a href="<?=$page?>?update=<?=$row['id']?>" class="btn btn-sm btn-info">Editar</a>
                            <a href="#"
                               data-href="<?=$page?>?delete=<?=$row['id']?>"
                               data-toggle="modal"
                               data-target="#confirm-delete"
                               class="btn btn-sm btn-danger">Excluir</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

        </div>
    </div>
</div>

<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>
