<?php
session_start();
require_once __DIR__ . '/auth/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit();
}

$userId = $_SESSION['user_id'];

// Fetch mining info
$stmt = $conn->prepare("SELECT mining_start_time, mining_balance FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($startTime, $miningBalance);
$stmt->fetch();
$stmt->close();

if (!$startTime) {
    echo json_encode([
        'success' => true,
        'mining' => false,
        'balance' => round($miningBalance, 8)
    ]);
    exit();
}

$now = time();
$elapsedHours = ($now - $startTime) / 3600;
$ratePerHour = 0.025;   // ✅ 0.025 GBL per hour
$maxHours = 8;
$maxReward = $ratePerHour * $maxHours; // ✅ 0.2 GBL

// Calculate mined amount for this session
$sessionMined = min($elapsedHours * $ratePerHour, $maxReward);

// Show live mining balance (accumulated + this session)
$currentBalance = $miningBalance + $sessionMined;

// If mining reached 8 hours -> finalize this session
if ($elapsedHours >= $maxHours) {
    $newBalance = $miningBalance + $maxReward; // ✅ add 0.2 GBL to total

    // Update DB: add earned GBL & stop mining
    $update = $conn->prepare("UPDATE users SET mining_balance = ?, mining_start_time = NULL WHERE id = ?");
    $update->bind_param("di", $newBalance, $userId);
    $update->execute();
    $update->close();

    echo json_encode([
        'success' => true,
        'mining' => false,
        'elapsed_hours' => $maxHours,
        'balance' => round($newBalance, 8),
        'remaining_seconds' => 0,
        'message' => '⏹ Mining session ended. Restart to mine again.'
    ]);
    exit();
} else {
    // Mining still ongoing -> show temporary balance
    $remainingSeconds = ($maxHours * 3600 - ($now - $startTime));

    echo json_encode([
        'success' => true,
        'mining' => true,
        'elapsed_hours' => round($elapsedHours, 4),
        'balance' => round($currentBalance, 8),
        'remaining_seconds' => $remainingSeconds
    ]);
    exit();
}
?>