<?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'];

// Check if mining session active (within 8 hours)
$stmt = $conn->prepare("SELECT mining_start_time, mining_balance FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($startTime, $currentBalance);
$stmt->fetch();
$stmt->close();

$now = time();
$eightHours = 8 * 3600;
$ratePerHour = 0.025;
$maxReward = $ratePerHour * 8; // 0.2 GBL max

if ($startTime === null) {
    echo json_encode(['success' => false, 'message' => 'No active mining session']);
    exit();
}

$elapsed = $now - $startTime;

if ($elapsed >= $eightHours) {
    // Mining finished - add max reward and reset
    $newBalance = $currentBalance + $maxReward;
    
    $stmt = $conn->prepare("UPDATE users SET mining_balance = ?, mining_start_time = NULL, last_mining_update = ? WHERE id = ?");
    $stmt->bind_param("dii", $newBalance, $now, $userId);
    $stmt->execute();
    $stmt->close();
    
    echo json_encode([
        'success' => true, 
        'total_balance' => round($newBalance, 8),
        'session_finished' => true,
        'message' => 'Mining session completed'
    ]);
    exit();
}

// Mining still active - calculate current progress
$sessionMined = min(($elapsed / 3600) * $ratePerHour, $maxReward);
$totalBalance = $currentBalance + $sessionMined;

// Update last check time
$stmt = $conn->prepare("UPDATE users SET last_mining_update = ? WHERE id = ?");
$stmt->bind_param("ii", $now, $userId);
$stmt->execute();
$stmt->close();

echo json_encode([
    'success' => true,
    'total_balance' => round($totalBalance, 8),
    'session_mined' => round($sessionMined, 8),
    'elapsed_hours' => round($elapsed / 3600, 2),
    'session_finished' => false
]);
?>