<?php
include 'config.php';

$conn->set_charset("utf8mb4");

function randomColor() {
    return sprintf("#%06X", mt_rand(0, 0xFFFFFF));
}

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

    $type      = $_POST['type'];
    $name      = $_POST['name'];
    $email     = $conn->real_escape_string($_POST['email']);
    $match_id  = intval($_POST['match_id']);
    $fcm_key   = $_POST['fcm_key'];
    $played_on = date('d-m-Y');

    // === ১. Email users table-এ আছে কিনা চেক ===
    $check_user_exists = $conn->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
    $check_user_exists->bind_param("s", $email);
    $check_user_exists->execute();
    if ($check_user_exists->get_result()->num_rows === 0) {
        echo "User Not Found";
        exit;
    }

    // === ২. Device Ban Check ===
    $dev_stmt = $conn->prepare("SELECT device_id FROM users WHERE email = ? LIMIT 1");
    $dev_stmt->bind_param("s", $email);
    $dev_stmt->execute();
    $dev_row = $dev_stmt->get_result()->fetch_assoc();
    $dev_stmt->close();

    if ($dev_row && !empty($dev_row['device_id'])) {
        $user_device_id = $dev_row['device_id'];

        $ban_stmt = $conn->prepare("SELECT ban_status FROM device_ban WHERE device_id = ? LIMIT 1");
        $ban_stmt->bind_param("s", $user_device_id);
        $ban_stmt->execute();
        $ban_row = $ban_stmt->get_result()->fetch_assoc();
        $ban_stmt->close();

        if ($ban_row && (int)$ban_row['ban_status'] === 1) {
            echo "Join Blocked";
            $conn->close();
            exit;
        }
    }

    // === Match Data: প্রথমে freefire টেবিলে খুঁজি, না পেলে match_schedule এ ===
    $match = null;
    $source_table = 'freefire'; // ডিফল্ট

    // freefire টেবিলে অনুসন্ধান
    $result = $conn->query("SELECT * FROM freefire WHERE id = '$match_id'");
    if ($result && $result->num_rows > 0) {
        $match = $result->fetch_assoc();
        $source_table = 'freefire';
    } else {
        // match_schedule টেবিলে অনুসন্ধান
        $result = $conn->query("SELECT * FROM match_schedule WHERE id = '$match_id'");
        if ($result && $result->num_rows > 0) {
            $match = $result->fetch_assoc();
            $source_table = 'match_schedule';
        }
    }

    if ($match) {
        $player      = $match['total_player'];
        $joiner      = $match['total_joiner'];
        $match_title = $match['match_title'];
        $base_fee    = $match['entry_fee'];

        $entry     = ($type === 'duo') ? 2 : (($type === 'squad') ? 4 : 1);
        $entry_fee = $base_fee * $entry;

        // === Already Joined Same Match চেক ===
        $chk2 = $conn->prepare("SELECT id FROM joiners WHERE email = ? AND match_id = ? LIMIT 1");
        $chk2->bind_param("si", $email, $match_id);
        $chk2->execute();
        $already2 = $chk2->get_result()->num_rows;

        if ($already2 > 0) {
            echo "Already Joined Match";
            exit;
        }

        if ($player >= $joiner + $entry) {

            $user = $conn->query("SELECT * FROM users WHERE email = '$email'")->fetch_assoc();

            if ($user) {
                $balance      = (int)$user['balance'];
                $winning      = (int)$user['winning'];
                $total_amount = $balance + $winning;

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

                    try {
                        $deduct_balance = min($balance, $entry_fee);
                        $remaining      = $entry_fee - $deduct_balance;
                        $deduct_winning = max(0, $remaining);

                        // Balance ও Winning Deduct
                        $conn->query("UPDATE users 
                            SET balance    = balance - $deduct_balance, 
                                winning    = winning - $deduct_winning, 
                                total_play = total_play + 1 
                            WHERE email = '$email'");

                        // Match Joiner Count Update (যে টেবিল থেকে ডেটা এসেছে সেখানে আপডেট)
                        $conn->query("UPDATE $source_table 
                            SET total_joiner = total_joiner + $entry 
                            WHERE id = $match_id");

                        // Statistics Insert
                        $conn->query("INSERT INTO statistics 
                            (email, type, match_id, match_title, played_on, paid, winnings)
                            VALUES 
                            ('$email', 'freefire', $match_id, '$match_title', '$played_on', $entry_fee, 0)
                            ON DUPLICATE KEY UPDATE 
                                paid = paid + VALUES(paid)");

                        // Join Entry
                        $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')");

                        // === Team Name Assign ===
                        $team_count_result = $conn->query(
                            "SELECT COUNT(DISTINCT team_color) as cnt 
                             FROM joiners 
                             WHERE match_id = $match_id"
                        );
                        $team_count_row = $team_count_result->fetch_assoc();
                        $new_team_name  = "Team " . ((int)$team_count_row['cnt'] + 1);
                        // === End ===

                        // Player Names
                        $names = [$name];
                        if ($type === 'duo') {
                            $names[] = $_POST['name2'];
                        }
                        if ($type === 'squad') {
                            $names[] = $_POST['name2'];
                            $names[] = $_POST['name3'];
                            $names[] = $_POST['name4'];
                        }

                        // Team Color
                        $team_color = randomColor();

                        // === Joiners Insert with is_leader ===
                        foreach ($names as $index => $player_name) {
                            $safe_name = $conn->real_escape_string($player_name);
                            $is_leader = ($index === 0) ? 1 : 0; // প্রথমজন Leader

                            $conn->query("INSERT IGNORE INTO joiners 
                                (name, type, mode, email, match_id, fcm_key, team_color, team_name, is_leader)
                                VALUES 
                                ('$safe_name', 'freefire', '$type', '$email', $match_id, '$fcm_key', '$team_color', '$new_team_name', $is_leader)");
                        }

                        $conn->commit();
                        echo "Join Successfully";

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

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

    $conn->close();

} else {
    echo "Invalid Request Method";
}
?>