<?php
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'];

    if ($type === 'getdata') {
        $id = $_POST['id'];
        $match_type = $_POST['match_type'];
        
        $query = "SELECT * FROM joiners WHERE type = '$match_type' AND match_id = '$id'";
        $result = mysqli_query($conn, $query);
        
        if ($result) {
            $data = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }

            if (!empty($data)) {
                echo json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                echo "No Joiner Found";
            }
        } else {
            echo "Error Getting Joiner: " . mysqli_error($conn);
        }
    }
    
    if ($type === 'statistics') {
        $email = $_POST['email'];
    
        $query = "SELECT * FROM statistics WHERE email = '$email'";
        $result = mysqli_query($conn, $query);
        
        if ($result) {
            $data = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }

            if (!empty($data)) {
                echo json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                echo "No Statistics Found";
            }
        } else {
            echo "Error Getting Statistics: " . mysqli_error($conn);
        }
    }

    if ($type === 'player_name_change') {
        $id = $_POST['id'];
        $name = $_POST['name'];

        $query = "UPDATE joiners SET name = '$name' WHERE id = '$id'";
        $result = mysqli_query($conn, $query);

        if ($result) {
            if (mysqli_affected_rows($conn) > 0) {
                echo "Player Name Updated Successfully";
            } else {
                echo "No Data Updated";
            }
        } else {
            echo "Error Updating Name: " . mysqli_error($conn);
        }
    }

    // ✅ FIXED TYPE: SEARCH JOINERS BY NAME WITHIN A SPECIFIC MATCH/ID
    if ($type === 'search') {
        $name = $_POST['name'];
        $id = $_POST['id']; // পোস্ট মেথডে পাঠানো আইডি

        // এখানে match_id = '$id' ব্যবহার করা হয়েছে যাতে ওই নির্দিষ্ট রো-এর জয়েনারদের পাওয়া যায়
        $query = "SELECT * FROM joiners WHERE match_id = '$id' AND name LIKE '$name%'";
        $result = mysqli_query($conn, $query);

        $data = [];
        if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }
        }

        // 🔥 সব সময় JSON ARRAY
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    
    mysqli_close($conn);
} else {
    echo "Invalid Request Method";
}
?>
