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

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$session_id = intval($_POST['session_id'] ?? 0);

if (!$session_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid session ID']);
    exit();
}

// Start transaction
$conn->begin_transaction();

try {
    // Get session details
    $query = "SELECT * FROM mining_sessions WHERE id = ? AND status = 'active'";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $session_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($session = $result->fetch_assoc()) {
        // Refund the user
        $refund_query = "UPDATE users SET account_balance = account_balance + ? WHERE id = ?";
        $refund_stmt = $conn->prepare($refund_query);
        $refund_stmt->bind_param("di", $session['amount'], $session['user_id']);
        $refund_stmt->execute();
        $refund_stmt->close();
        
        // Update session status
        $update_query = "UPDATE mining_sessions SET status = 'cancelled' WHERE id = ?";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param("i", $session_id);
        $update_stmt->execute();
        $update_stmt->close();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Session cancelled and user refunded']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Session not found or not active']);
    }
    
    $stmt->close();
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>