<?php
include 'config.php';

function respond($msg) {
    echo $msg;
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond("Invalid Request Method");
}

$admin_username = $_POST['admin_username'];
$admin_password = $_POST['admin_password'];

$admin_stmt = $conn->prepare("SELECT username FROM admin WHERE username = ? AND password = ?");
$admin_stmt->bind_param("ss", $admin_username, $admin_password);
$admin_stmt->execute();
$admin_result = $admin_stmt->get_result();

if ($admin_result->num_rows === 0) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied"], JSON_PRETTY_PRINT);
    $admin_stmt->close();
    $conn->close();
    exit();
}

$owner_row = $admin_result->fetch_assoc();
$owner_name = $owner_row['username'];
$admin_stmt->close();

function get_match_title($conn, $match_id, $match_type) {
    $table = "`" . $conn->real_escape_string($match_type) . "`";
    $stmt = $conn->prepare("SELECT match_title FROM $table WHERE id = ?");
    $stmt->bind_param("i", $match_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $title = null;
    if ($row = $res->fetch_assoc()) {
        $title = $row['match_title'];
    }
    $stmt->close();
    return $title;
}

function log_refund($conn, $moderator, $action, $match_id, $match_type, $match_title = null, $joiner_id = null, $refunded_email = null, $refunded_count = 1, $refunded_amount = 0.00) {
    $log_stmt = $conn->prepare("INSERT INTO refund_logs (moderator_username, action, match_id, match_type, match_title, joiner_id, refunded_email, refunded_count, refunded_amount, refunded_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $log_stmt->bind_param("ssissisid", $moderator, $action, $match_id, $match_type, $match_title, $joiner_id, $refunded_email, $refunded_count, $refunded_amount);
    $log_stmt->execute();
    $log_stmt->close();
}

function log_statistics_refund($conn, $match_id, $match_type, $email, $refund_amount) {
    $refund_reason = 'If canceled, entry fee will be 100% refunded.';
    $stmt = $conn->prepare("INSERT INTO statistics (match_id, type, email, refund_amount, refund_reason) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE refund_amount = refund_amount + VALUES(refund_amount), refund_reason = VALUES(refund_reason)");
    $stmt->bind_param("issds", $match_id, $match_type, $email, $refund_amount, $refund_reason);
    $stmt->execute();
    $stmt->close();
}

$action = isset($_POST['action']) ? trim($_POST['action']) : 'single';
$match_type = isset($_POST['match_type']) ? trim($_POST['match_type']) : (isset($_POST['type']) ? trim($_POST['type']) : '');
$match_id = isset($_POST['match_id']) ? intval($_POST['match_id']) : 0;
$entry_fee_post = isset($_POST['entry_fee']) ? floatval($_POST['entry_fee']) : 0.0;
$joiner_id = isset($_POST['joiner_id']) ? intval($_POST['joiner_id']) : 0;
$email = isset($_POST['email']) ? trim($_POST['email']) : '';

try {
    if ($action === 'single') {
        if (!$email || !$joiner_id || !$match_id) {
            respond("Missing parameters (email, joiner_id, match_id required)");
        }
        if (empty($match_type)) {
            $stmt = $conn->prepare("SELECT type FROM joiners WHERE id = ? LIMIT 1");
            $stmt->bind_param("i", $joiner_id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                $match_type = $row['type'];
            } else {
                respond("Joiner not found or match_type not provided");
            }
            $stmt->close();
        }
        $match_table = "`" . $conn->real_escape_string($match_type) . "`";
        $conn->begin_transaction();

        $stmt = $conn->prepare("SELECT email FROM joiners WHERE id = ? AND type = ?");
        $stmt->bind_param("is", $joiner_id, $match_type);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res->num_rows === 0) {
            $stmt->close();
            $conn->rollback();
            respond("Joiner not found");
        }
        $row = $res->fetch_assoc();
        $target_email = $row['email'];
        $stmt->close();

        $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE email = ?");
        $stmt->bind_param("ds", $entry_fee_post, $target_email);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error updating user balance: " . $conn->error);
        }
        if ($stmt->affected_rows === 0) {
            $stmt->close();
            $conn->rollback();
            respond("User not found or balance not updated (email mismatch)");
        }
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM joiners WHERE id = ? AND type = ?");
        $stmt->bind_param("is", $joiner_id, $match_type);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error deleting joiner: " . $conn->error);
        }
        $stmt->close();

        $stmt = $conn->prepare("UPDATE $match_table SET total_joiner = GREATEST(total_joiner - 1, 0) WHERE id = ?");
        $stmt->bind_param("i", $match_id);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error updating match total_joiner: " . $conn->error);
        }
        $stmt->close();

        $stmt = $conn->prepare("UPDATE join_entry SET status = '+refunded' WHERE email = ? AND match_id = ?");
        $stmt->bind_param("si", $target_email, $match_id);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error updating join_entry: " . $conn->error);
        }
        $stmt->close();

        $match_title = get_match_title($conn, $match_id, $match_type);
        log_refund($conn, $owner_name, 'single', $match_id, $match_type, $match_title, $joiner_id, $target_email, 1, $entry_fee_post);
        log_statistics_refund($conn, $match_id, $match_type, $target_email, $entry_fee_post);

        $conn->commit();
        respond("Refund Successfully (single)");

    } elseif ($action === 'all') {
        if (!$match_id) {
            respond("Missing match_id");
        }
        if (empty($match_type)) {
            $stmt = $conn->prepare("SELECT DISTINCT type FROM joiners WHERE match_id = ? LIMIT 1");
            $stmt->bind_param("i", $match_id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                $match_type = $row['type'];
            } else {
                respond("No joiners found and match_type not provided");
            }
            $stmt->close();
        }
        $match_table = "`" . $conn->real_escape_string($match_type) . "`";
        $conn->begin_transaction();

        $stmt = $conn->prepare("SELECT id, email FROM joiners WHERE type = ? AND match_id = ?");
        $stmt->bind_param("si", $match_type, $match_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $joiners = $res->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (count($joiners) === 0) {
            $conn->rollback();
            respond("No joiners found for this match");
        }

        $match_title = get_match_title($conn, $match_id, $match_type);
        $updUser   = $conn->prepare("UPDATE users SET balance = balance + ? WHERE email = ?");
        $delJoiner = $conn->prepare("DELETE FROM joiners WHERE id = ?");
        $updEntry  = $conn->prepare("UPDATE join_entry SET status = '+refunded' WHERE email = ? AND match_id = ?");
        $refunded_count = 0;

        foreach ($joiners as $j) {
            $updUser->bind_param("ds", $entry_fee_post, $j['email']);
            if (!$updUser->execute()) {
                $updUser->close();
                $conn->rollback();
                respond("Error updating user balance: " . $conn->error);
            }
            if ($updUser->affected_rows === 0) {
                $updUser->close();
                $conn->rollback();
                respond("User not found for email: " . $j['email']);
            }

            $delJoiner->bind_param("i", $j['id']);
            $delJoiner->execute();

            $updEntry->bind_param("si", $j['email'], $match_id);
            $updEntry->execute();

            log_refund($conn, $owner_name, 'all', $match_id, $match_type, $match_title, $j['id'], $j['email'], 1, $entry_fee_post);
            log_statistics_refund($conn, $match_id, $match_type, $j['email'], $entry_fee_post);
            $refunded_count++;
        }

        $updUser->close();
        $delJoiner->close();
        $updEntry->close();

        $stmt = $conn->prepare("UPDATE $match_table SET total_joiner = GREATEST(total_joiner - ?, 0) WHERE id = ?");
        $stmt->bind_param("ii", $refunded_count, $match_id);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error updating match total_joiner: " . $conn->error);
        }
        $stmt->close();

        $stmt = $conn->prepare("UPDATE join_entry SET status = '+refunded' WHERE match_id = ?");
        $stmt->bind_param("i", $match_id);
        if (!$stmt->execute()) {
            $stmt->close();
            $conn->rollback();
            respond("Error updating join_entry: " . $conn->error);
        }
        $stmt->close();

        $conn->commit();
        respond("Refunded All Joiners");

    } elseif ($action === 'joiners') {
        $match_id = isset($_POST['match_id']) ? intval($_POST['match_id']) : 0;
        if (!$match_id) {
            respond("Missing match_id");
        }
        $query = $conn->query("SELECT COUNT(*) AS total FROM joiners WHERE match_id = $match_id");
        if ($query && $row = $query->fetch_assoc()) {
            echo json_encode(["match_id" => $match_id, "total_joiners" => (int)$row['total']]);
        } else {
            echo json_encode(["match_id" => $match_id, "total_joiners" => 0]);
        }

    } elseif ($action === 'kill') {
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        $kill_count = isset($_POST['kill_count']) ? intval($_POST['kill_count']) : 0;
        $balance_add = isset($_POST['balance_add']) ? floatval($_POST['balance_add']) : 0.0;

        if (empty($email)) {
            respond("Email is required");
        }
        if ($kill_count == 0 && $balance_add == 0) {
            respond("At least one of kill_count or balance_add must be greater than zero");
        }

        $stmt = $conn->prepare("UPDATE users SET total_kill = total_kill + ?, balance = balance + ? WHERE email = ?");
        $stmt->bind_param("ids", $kill_count, $balance_add, $email);
        if (!$stmt->execute()) {
            $stmt->close();
            respond("Error updating user stats: " . $conn->error);
        }
        if ($stmt->affected_rows === 0) {
            $stmt->close();
            respond("User not found");
        }
        $stmt->close();

        echo json_encode(["status" => "success", "message" => "Player stats updated successfully"]);

    } else {
        respond("Unknown action");
    }
} catch (Exception $e) {
    if ($conn->in_transaction) {
        $conn->rollback();
    }
    respond("Error: " . $e->getMessage());
}
?>