<?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 already mining
$stmt = $conn->prepare("SELECT mining_start_time FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($startTime);
$stmt->fetch();
$stmt->close();

$now = time();
$eightHours = 8 * 3600;

if ($startTime !== null && ($now - $startTime) < $eightHours) {
    $remaining = $eightHours - ($now - $startTime);
    echo json_encode([
        'success' => false, 
        'message' => 'Mining already in progress. Please wait until it finishes.',
        'remaining_seconds' => $remaining
    ]);
    exit();
}

// Start mining
$stmt = $conn->prepare("UPDATE users SET mining_start_time = ?, last_mining_update = ? WHERE id = ?");
$stmt->bind_param("iii", $now, $now, $userId);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Mining started', 'start_time' => $now]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to start mining']);
}

$stmt->close();
?>