<?php
header('Content-Type: application/json');
include 'config.php';

session_start();

$admin_authenticated = false;

if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true && isset($_SESSION['admin_user'])) {
    $mod_username = $conn->real_escape_string($_SESSION['admin_user']);
    $query = $conn->query("SELECT extra_json FROM modarator_permissions WHERE username = '$mod_username' LIMIT 1");
    
    if ($query && $query->num_rows > 0) {
        $user_data = $query->fetch_assoc();
        if (!empty($user_data['extra_json'])) {
            $extra_data = json_decode($user_data['extra_json'], true);
            if (isset($extra_data['withdrawals']) && $extra_data['withdrawals'] === 'Yes') {
                $admin_authenticated = true;
            }
        }
    }
}

if (!$admin_authenticated) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied. You do not have permission."]);
    exit;
}

$type = $_POST['type'] ?? '';

if ($type === 'total_unpaid') {
    $result = $conn->query("SELECT SUM(amount) as total FROM withdraw WHERE status='Pending'");
    $total = 0;
    if ($result && $row = $result->fetch_assoc()) {
        $total = (int)$row['total'];
    }
    echo json_encode(["status" => "success", "total" => $total]);
    exit;
}

if ($type === 'get_all') {
    $status = $conn->real_escape_string($_POST['status'] ?? '');
    $page = max(1, (int)($_POST['page'] ?? 1));
    $per_page = max(1, (int)($_POST['per_page'] ?? 20));
    $offset = ($page - 1) * $per_page;
    $where = "";
    
    if ($status && in_array($status, ['Pending', 'Success', 'Failed'])) {
        $where = " WHERE status = '$status'";
    }
    
    $countQuery = "SELECT COUNT(*) as total FROM withdraw" . $where;
    $countResult = $conn->query($countQuery);
    $total = $countResult->fetch_assoc()['total'] ?? 0;
    $last_page = max(1, ceil($total / $per_page));
    
    $sql = "SELECT * FROM withdraw" . $where . " ORDER BY id DESC LIMIT $offset, $per_page";
    $result = $conn->query($sql);
    $data = [];
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    
    echo json_encode([
        "status" => "success",
        "data" => $data,
        "total" => (int)$total,
        "current_page" => $page,
        "per_page" => $per_page,
        "last_page" => $last_page
    ]);
    exit;
}

if ($type === 'success') {
    $id = (int)($_POST['id'] ?? 0);
    
    if (!$id) {
        echo json_encode(["status" => "error", "message" => "Missing ID"]);
        exit;
    }
    
    $check = $conn->query("SELECT status FROM withdraw WHERE id = $id");
    if ($check && $row = $check->fetch_assoc()) {
        if ($row['status'] !== 'Pending') {
            echo json_encode(["status" => "error", "message" => "Request already processed"]);
            exit;
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Request not found"]);
        exit;
    }
    
    $update = $conn->query("UPDATE withdraw SET status = 'Success' WHERE id = $id");
    if ($update) {
        echo json_encode(["status" => "success", "message" => "Withdraw approved successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to approve"]);
    }
    exit;
}

if ($type === 'failed') {
    $id = (int)($_POST['id'] ?? 0);
    
    if (!$id) {
        echo json_encode(["status" => "error", "message" => "Missing ID"]);
        exit;
    }
    
    $get = $conn->query("SELECT amount, email FROM withdraw WHERE id = $id AND status = 'Pending'");
    if (!$get || $get->num_rows === 0) {
        echo json_encode(["status" => "error", "message" => "Request not found or already processed"]);
        exit;
    }
    
    $row = $get->fetch_assoc();
    $amount = (int)$row['amount'];
    $withdraw_email = $conn->real_escape_string($row['email']);
    
    $refund = $conn->query("UPDATE users SET winning = winning + $amount WHERE email = '$withdraw_email'");
    if (!$refund) {
        echo json_encode(["status" => "error", "message" => "Failed to refund user"]);
        exit;
    }
    
    $update = $conn->query("UPDATE withdraw SET status = 'Failed' WHERE id = $id");
    if ($update) {
        echo json_encode(["status" => "success", "message" => "Withdraw rejected and refunded"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to update status"]);
    }
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid type"]);
$conn->close();
?>
