<?php
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'];
    $entry = $_POST['entry'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $match_id = $_POST['match_id'];
    $fcm_key = $_POST['fcm_key'];
    $played_on = date('d-m-Y');
    
    
    
    $stmt = $conn->prepare("SELECT key_value FROM api_keys ORDER BY    id DESC LIMIT 1");
     $stmt->execute();
     $result = $stmt->get_result();
     $row = $result->fetch_assoc();
     $db_key = $row['key_value'] ?? '';

     if (($_POST["Authorization"] ?? '') !== $db_key) {
    echo json_encode(["status" => "error", "message" => "Unauthorized request"]);
    exit;
}
    
    

    $ffresult = $conn->query("SELECT * FROM ludoking WHERE id = '$match_id'");

    if ($ffresult->num_rows > 0) {
        $ffrow = $ffresult->fetch_assoc();
        $player = $ffrow["total_player"];
        $joiner = $ffrow["total_joiner"];
        $match_title = $ffrow["match_title"];

        $entry_fee = ($type === 'duo') ? $ffrow["entry_fee"] * 2 : $ffrow["entry_fee"];
        $entry = ($type === 'duo') ? 2 : 1;

        if ($player >= $joiner + $entry) {
            $result = $conn->query("SELECT * FROM users WHERE email = '$email'");

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $balance = $row["balance"];

                if ($balance >= $entry_fee) {
                    $conn->begin_transaction();

                    try {
                        $conn->query("UPDATE users SET balance = balance - $entry_fee, total_play = total_play + 1 WHERE email = '$email'");
                        $conn->query("UPDATE ludoking SET total_joiner = total_joiner + $entry WHERE id = $match_id");

                        $conn->query("INSERT INTO statistics (email, type, match_id, match_title, played_on, paid)
                                      VALUES ('$email', 'ludoking', '$match_id', '$match_title', '$played_on', '$entry_fee')");

                        $conn->query("INSERT INTO join_entry (email, match_id, match_title, entry_fee, joined_on, status)
                                      VALUES ('$email', '$match_id', '$match_title', '$entry_fee', '$played_on', '-debited')");

                        $conn->query("INSERT INTO joiners (name, type, email, match_id, fcm_key)
                                      VALUES ('$name', 'ludoking', '$email', '$match_id', '$fcm_key')");

                        if ($type === 'duo') {
                            $name2 = $_POST['name2'];
                            $conn->query("INSERT INTO joiners (name, type, email, match_id, fcm_key)
                                          VALUES ('$name2', 'ludoking', '$email', '$match_id', '$fcm_key')");
                        }

                        $conn->commit();
                        echo "Join Successfully";
                    } catch (Exception $e) {
                        $conn->rollback();
                        echo "Error Joining: " . $conn->error;
                    }

                } else {
                    include 'multipleff.php';
                }
            } else {
                echo "No User Found";
            }
        } else {
            echo "Match Is Full";
        }
    } else {
        echo "No Matches Found";
    }

    $conn->close();
} else {
    echo "Invalid Request Method";
}
?>