<?php
include 'config.php';

function clean_value($conn, $value) {
    return mysqli_real_escape_string($conn, trim((string)$value));
}

function is_enabled_true($value) {
    $value = strtolower(trim((string)$value));
    return in_array($value, ['true', '1', 'yes', 'on'], true);
}

function get_match_settings($conn, $table, $id) {
    $table = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $id = clean_value($conn, $id);

    $query = "SELECT room_pass, room_id, player_name_change FROM `$table` WHERE id = '$id' LIMIT 1";
    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        return mysqli_fetch_assoc($result);
    }

    return null;
}

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

    if ($type === 'getdata') {
        $id = clean_value($conn, $_POST['id'] ?? '');
        $match_type = clean_value($conn, $_POST['match_type'] ?? '');
        $token = $_POST['token'] ?? '';

        $user_email = "";
        if (!empty($token)) {
            $token_escaped = clean_value($conn, $token);
            $user_query = mysqli_query($conn, "SELECT email FROM users WHERE token='$token_escaped' LIMIT 1");
            if ($user_query && mysqli_num_rows($user_query) > 0) {
                $user_row = mysqli_fetch_assoc($user_query);
                $user_email = $user_row['email'];
            }
        }

        $query = "SELECT id, name, winning, total_kill, mode, team_color, team_name, is_leader, email 
                  FROM joiners 
                  WHERE type = '$match_type' AND match_id = '$id'
                  ORDER BY team_name ASC, is_leader DESC";
        $result = mysqli_query($conn, $query);

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

            if (!empty($rows)) {
                $teams = [];
                foreach ($rows as $row) {
                    $team = $row['team_name'];
                    if (!isset($teams[$team])) {
                        $teams[$team] = [
                            'team_name' => $team,
                            'team_color' => $row['team_color'],
                            'players' => []
                        ];
                    }

                    $teams[$team]['players'][] = [
                        'id' => $row['id'],
                        'name' => $row['name'],
                        'winning' => $row['winning'],
                        'total_kill' => $row['total_kill'],
                        'mode' => $row['mode'],
                        'is_leader' => (int)$row['is_leader'],
                        'is_owner' => ($row['email'] === $user_email && !empty($user_email)) ? "true" : "false"
                    ];
                }

                $response = array_values($teams);
                echo json_encode($response, JSON_UNESCAPED_UNICODE);
            } else {
                echo "No Joiner Found";
            }
        } else {
            echo "Error Getting Joiner: " . mysqli_error($conn);
        }
    }

    if ($type === 'statistics') {
        $email = clean_value($conn, $_POST['email'] ?? '');

        $query = "SELECT * FROM statistics WHERE email = '$email'";
        $result = mysqli_query($conn, $query);
        $data = [];

        if ($result) {
            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 === 'join_entry') {
        $email = clean_value($conn, $_POST['email'] ?? '');

        $query = "SELECT * FROM join_entry WHERE email = '$email'";
        $result = mysqli_query($conn, $query);
        $data = [];

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

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

    if ($type === 'player_name_change') {
        $id = clean_value($conn, $_POST['id'] ?? '');
        $new_name = clean_value($conn, $_POST['name'] ?? '');
        $change_id = clean_value($conn, $_POST['change_id'] ?? '');
        $token = $_POST['token'] ?? '';

        if ($id === '' || $new_name === '' || $change_id === '' || $token === '') {
            echo "Invalid Request";
            mysqli_close($conn);
            exit;
        }

        // ---- Find user by token (from users table) ----
        $token_escaped = clean_value($conn, $token);
        $user_query = mysqli_query($conn, "SELECT email, balance, winning FROM users WHERE token = '$token_escaped' LIMIT 1");

        if (!$user_query || mysqli_num_rows($user_query) === 0) {
            echo "Invalid Token";
            mysqli_close($conn);
            exit;
        }

        $user_row = mysqli_fetch_assoc($user_query);
        $user_email = $user_row['email'];
        $user_balance = (float)$user_row['balance'];
        $user_winning = (float)$user_row['winning'];

        $freefire_row = get_match_settings($conn, 'freefire', $id);
        $schedule_row = null;
        $allowed_row = null;

        if ($freefire_row) {
            if (is_enabled_true($freefire_row['player_name_change'])) {
                $allowed_row = $freefire_row;
            } else {
                $schedule_row = get_match_settings($conn, 'match_schedule', $id);
                if ($schedule_row && is_enabled_true($schedule_row['player_name_change'])) {
                    $allowed_row = $schedule_row;
                }
            }
        } else {
            $schedule_row = get_match_settings($conn, 'match_schedule', $id);
            if ($schedule_row && is_enabled_true($schedule_row['player_name_change'])) {
                $allowed_row = $schedule_row;
            }
        }

        if (!$allowed_row) {
            if (($freefire_row && !is_enabled_true($freefire_row['player_name_change'])) || ($schedule_row && !is_enabled_true($schedule_row['player_name_change']))) {
                echo "Name Change Not Allowed";
            } else {
                echo "No Match Found";
            }
        } else {
            $room_pass = strtoupper(trim((string)$allowed_row['room_pass']));
            $room_id = strtoupper(trim((string)$allowed_row['room_id']));

            if ($room_pass === 'NO' && $room_id === 'NO') {

                // ---- Balance / Winning deduction (1 Tk per name change) ----
                $deduct_from = null; // 'balance' or 'winning'

                if ($user_balance > 0) {
                    $deduct_from = 'balance';
                } elseif ($user_winning > 0) {
                    $deduct_from = 'winning';
                }

                if ($deduct_from === null) {
                    echo "Insufficient Balance";
                    mysqli_close($conn);
                    exit;
                }

                $email_escaped = clean_value($conn, $user_email);

                if ($deduct_from === 'balance') {
                    $deduct_query = "UPDATE users SET balance = balance - 1 WHERE token = '$token_escaped' AND balance > 0";
                } else {
                    $deduct_query = "UPDATE users SET winning = winning - 1 WHERE token = '$token_escaped' AND winning > 0";
                }

                $deduct_result = mysqli_query($conn, $deduct_query);

                if (!$deduct_result || mysqli_affected_rows($conn) === 0) {
                    echo "Insufficient Balance";
                    mysqli_close($conn);
                    exit;
                }

                // ---- Proceed with existing name update logic ----
                $update_query = "UPDATE joiners SET name = '$new_name' WHERE id = '$change_id'";
                $update_result = mysqli_query($conn, $update_query);

                if ($update_result) {
                    if (mysqli_affected_rows($conn) > 0) {
                        echo "Name Updated Successfully";
                    } else {
                        // Name update failed after deduction -> refund
                        if ($deduct_from === 'balance') {
                            mysqli_query($conn, "UPDATE users SET balance = balance + 1 WHERE token = '$token_escaped'");
                        } else {
                            mysqli_query($conn, "UPDATE users SET winning = winning + 1 WHERE token = '$token_escaped'");
                        }
                        echo "No Joiner Found With This ID";
                    }
                } else {
                    // Update query error -> refund
                    if ($deduct_from === 'balance') {
                        mysqli_query($conn, "UPDATE users SET balance = balance + 1 WHERE token = '$token_escaped'");
                    } else {
                        mysqli_query($conn, "UPDATE users SET winning = winning + 1 WHERE token = '$token_escaped'");
                    }
                    echo "Error Updating Name: " . mysqli_error($conn);
                }
            } else {
                echo "Already Match Started";
            }
        }
    }

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