<?php
require_once '../config.php';
session_start();

if (!isset($_SESSION['userid'])) {
    header("Location: ../login/");
    exit();
}

$userid = $_SESSION['userid'];
$page = 'inicio'; // Set the active page for the header

// Database queries
$sql = "SELECT * FROM current_tickets WHERE userid = ? ORDER BY expiredate DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userid);
$stmt->execute();
$result = $stmt->get_result();

$id = $ticketname = $buydate = $expiredate = $opportunities = null;
$currentDate = new DateTime();
$currentDate = $currentDate->format('Y-m-d');

$validTicketFound = false;

while ($row = $result->fetch_assoc()) {
    $expireDate = new DateTime($row['expiredate']);
    $expireDate = $expireDate->format('Y-m-d');

    if ($expireDate >= $currentDate) {
        $id = $row['id'];
        $ticketname = $row['ticketname'];
        $buydate = $row['buydate'];
        $expiredate = $row['expiredate'];
        $opportunities = $row['opportunities'];
        $validTicketFound = true;
        break;
    }
}

$stmt->close();

$currentDate = new DateTime();

if (!empty($expiredate) && strtotime($expiredate) !== false) {
    $expireDate = new DateTime($expiredate);
    $interval = $currentDate->diff($expireDate);
    $daysRemaining = $interval->days;

    if ($expireDate < $currentDate) {
        $daysRemaining = "-";
    } else {
        $interval = $currentDate->diff($expireDate);
        $daysRemaining = $interval->days;

        if ($expireDate >= $currentDate) {
            $daysRemaining++;
        }
    }
} else {
    $daysRemaining = "-";
}

$sql_latest_training = "SELECT workout_date FROM workout_stats WHERE userid = ? ORDER BY workout_date DESC LIMIT 1";
$stmt_latest_training = $conn->prepare($sql_latest_training);
$stmt_latest_training->bind_param("i", $userid);
$stmt_latest_training->execute();
$result_latest_training = $stmt_latest_training->get_result();
$latest_training = ($result_latest_training->num_rows > 0) ? $result_latest_training->fetch_assoc()['workout_date'] : $translations["n/a"];
$stmt_latest_training->close();

$sql = "SELECT firstname, lastname, profile_balance FROM users WHERE userid = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userid);
$stmt->execute();
$stmt->bind_result($firstname, $lastname, $profile_balance);
$stmt->fetch();
$stmt->close();

$conn->close();

// QR Code Generation
require __DIR__ . '/../vendor/autoload.php';

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\Label\Font\NotoSans;

$filename = __DIR__ . "/../assets/img/logincard/{$userid}.png";
$logoPath = 'https://gymoneglobal.com/assets/img/logo.png';

if (!file_exists($filename)) {
    try {
        $result = Builder::create()
            ->writer(new PngWriter())
            ->data($userid)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(5)
            ->logoPath($logoPath)
            ->logoResizeToWidth(100)
            ->labelText($firstname . ' ' . $lastname)
            ->labelFont(new NotoSans(20))
            ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();

        $result->saveToFile($filename);
        header("Refresh:2");
    } catch (Exception $e) {
        error_log('Fallo en la generación del código QR: ' . $e->getMessage());
        $qr_error = $translations['qr_code_error_message'] ?? 'Error al generar el código QR. Por favor, intente de nuevo más tarde.';
    }
}

require_once '../assets/templates/header-dashboard.php';
?>

<div class="d-none topnav d-sm-inline-block">
    <h4><?php echo $translations["welcome"]; ?> <?php echo $lastname; ?> <?php echo $firstname; ?></h4>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#logoutModal">
        <?php echo $translations["logout"]; ?>
    </button>
</div>
<div class="row">
    <div class="col-sm-3">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title fw-semibold"><?php echo $translations["currentticket"]; ?></h4>
                <h1><strong><?php if (!empty($ticketname)): ?><?php echo $ticketname; ?><?php else: ?>-<?php endif; ?></strong></h1>
            </div>
        </div>
    </div>
    <div class="col-sm-3">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title fw-semibold"><?php echo $translations["lastworkout"]; ?></h4>
                <h1><strong><?= $latest_training;?></strong></h1>
            </div>
        </div>
    </div>
    <div class="col-sm-3">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title fw-semibold"><?php echo $translations["remainingdays"]; ?></h4>
                <h1><strong><?php echo $daysRemaining; ?> </strong><?php echo $translations["day"]; ?></h1>
            </div>
        </div>
    </div>
    <div class="col-sm-3">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title fw-semibold"><?php echo $translations["profilebalance"]; ?></h4>
                <h1><strong><?php echo $profile_balance;?></strong><?php echo $currency; ?></h1>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-sm-3">
        <div class="card">
            <div class="card-body text-center">
                <?php
                if (isset($qr_error)) {
                    echo "<p class='text-danger'>{$qr_error}</p>";
                } elseif (file_exists($filename)) {
                    echo "<img class='img img-fluid' src='../assets/img/logincard/{$userid}.png' alt='{$firstname}-{$lastname}-{$userid}'>";
                } else {
                    echo "<h2 class='lead'>{$translations["qrgenerateing"]}</h2>";
                }
                ?>
            </div>
        </div>
    </div>
</div>

<?php
require_once '../assets/templates/footer-dashboard.php';
?>