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

session_start();

// Hardcoded Admin Credentials
$VALID_USERNAME = 'SKM eSPORTS';
$VALID_PASSWORD = '2580';

$admin_authenticated = false;
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    $admin_authenticated = true;
}

if (!$admin_authenticated) {
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    if ($admin_username === $VALID_USERNAME && $admin_password === $VALID_PASSWORD) {
        $admin_authenticated = true;
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_username'] = $admin_username;
    }
}

if (!$admin_authenticated) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied. Please login."]);
    exit;
}

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

// Helper
function getAppSettings($conn) {
    $settings = ["min_firstdp" => 0, "referral_bonus" => 0];
    $query = "SELECT min_firstdp, referral_bonus FROM appinfo LIMIT 1";
    $result = $conn->query($query);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $settings["min_firstdp"] = (int)$row["min_firstdp"];
        $settings["referral_bonus"] = (int)$row["referral_bonus"];
    }
    return $settings;
}

if ($type === 'pending') {
    $result = $conn->query("SELECT * FROM addmoney WHERE status='Pending' ORDER BY id DESC");
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode(["status" => "success", "data" => $data]);

} elseif ($type === 'success') {
    $id = $_POST['id'] ?? 0;
    if (!$id) {
        echo json_encode(["status" => "error", "message" => "Missing ID"]);
        exit;
    }

    $stmt = $conn->prepare("SELECT * FROM addmoney WHERE id = ? AND status = 'Pending'");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        echo json_encode(["status" => "error", "message" => "Request not found or already processed"]);
        $stmt->close();
        exit;
    }
    $row = $result->fetch_assoc();
    $amount = (int)$row['amount'];
    $email = $row['email'];
    $stmt->close();

    // Bonus check
    $bonus = 0;
    $checkBonus = $conn->query("SELECT bonus_amount FROM deposits WHERE deposit_amount = $amount LIMIT 1");
    if ($checkBonus && $checkBonus->num_rows > 0) {
        $bonusRow = $checkBonus->fetch_assoc();
        $bonus = (int)$bonusRow['bonus_amount'];
    }
    $totalAdd = $amount + $bonus;

    // Update user balance
    $updateUser = $conn->prepare("UPDATE users SET balance = balance + ? WHERE email = ?");
    $updateUser->bind_param("is", $totalAdd, $email);
    if (!$updateUser->execute()) {
        echo json_encode(["status" => "error", "message" => "Failed to update user balance"]);
        $updateUser->close();
        exit;
    }
    $updateUser->close();

    // Update status
    $updateStatus = $conn->prepare("UPDATE addmoney SET status='Success' WHERE id=?");
    $updateStatus->bind_param("i", $id);
    if (!$updateStatus->execute()) {
        echo json_encode(["status" => "error", "message" => "Failed to update request status"]);
        $updateStatus->close();
        exit;
    }
    $updateStatus->close();

    // Referral bonus
    $checkRef = $conn->query("SELECT username, first_deposit_done, referred_by FROM users WHERE email='$email'");
    if ($checkRef->num_rows > 0) {
        $userData = $checkRef->fetch_assoc();
        if ($userData['first_deposit_done'] == 0 && !empty($userData['referred_by'])) {
            $settings = getAppSettings($conn);
            $min_firstdp = $settings['min_firstdp'];
            $refBonus = $settings['referral_bonus'];
            if ($amount >= $min_firstdp) {
                $referred_by = $userData['referred_by'];
                $conn->query("UPDATE users SET refer_earn = refer_earn + $refBonus, balance = balance + $refBonus WHERE username = '$referred_by'");
            }
            $conn->query("UPDATE users SET first_deposit_done=1 WHERE email='$email'");
        }
    }

    echo json_encode(["status" => "success", "message" => "Payment approved successfully"]);

} elseif ($type === 'failed') {
    $id = $_POST['id'] ?? 0;
    if (!$id) {
        echo json_encode(["status" => "error", "message" => "Missing ID"]);
        exit;
    }
    $stmt = $conn->prepare("UPDATE addmoney SET status='Failed' WHERE id=? AND status='Pending'");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Payment marked as failed"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to update status"]);
    }
    $stmt->close();

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

} elseif ($type === 'get_all') {
    $status = $_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'";
    }
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM addmoney" . $where;
    $countResult = $conn->query($countQuery);
    $total = $countResult->fetch_assoc()['total'] ?? 0;
    $last_page = ceil($total / $per_page);
    
    // Get data
    $sql = "SELECT * FROM addmoney" . $where . " ORDER BY id DESC LIMIT $offset, $per_page";
    $result = $conn->query($sql);
    $data = [];
    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
    ]);

} else {
    echo json_encode(["status" => "error", "message" => "Invalid type"]);
}

$conn->close();
?>