<?php
require '../config/db.php';
require_once '../app/models/user.php';
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["checkin_diario"])) {

    if ($user['last_checkin'] < date("Y-m-d H:i:s")) {
        $balance = 0.50;

        $stmtUpdateUser = $pdo->prepare("UPDATE users SET balance = balance + :balance, last_checkin = :last_checkin, count_checkin = count_checkin + 1 WHERE id = :id");
        $stmtUpdateUser->execute([
            ':balance' => $balance,
            ':id' => $user['id'],
            ':last_checkin' => date('Y-m-d H:i:s', strtotime('+ 24hours'))
        ]);

        $_SESSION['toastMessage'] = $toastMessage = "Check-in feito! R$ {$balance} adicionados à sua conta. Volte amanhã para continuar ganhando.";
        $_SESSION['toastType'] = $toastType = 'success';
        $_SESSION['success_value'] = $balance;
        $_SESSION['show_modal'] = true;
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    } else {
        $_SESSION['toastMessage'] = $toastMessage = 'Você já efetuou o check-in dentro do período de 24 horas.';
        $_SESSION['toastType'] = $toastType = 'error';
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }
}