<?php
require_once "config.php";

session_start();
date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

if (empty($_SESSION['auth_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$role = $_SESSION['auth_role'];
$username = $_SESSION['auth_username'];
$is_super = ($role === 'admin');

$can_refund = false;
if ($is_super) {
    $can_refund = true;
} else {
    $stmt = $conn->prepare("SELECT refund_send FROM Zabbar_Admin_Permission WHERE username = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (($row['refund_send'] ?? 'No') === 'Yes') {
            $can_refund = true;
        }
    }
    $stmt->close();
}

function respond_json($status, $message, $data = []) {
    header('Content-Type: application/json');
    echo json_encode(array_merge(["status" => $status, "message" => $message], $data));
    exit;
}

function log_refund($conn, $moderator, $action, $match_id, $match_type, $match_title, $joiner_id, $refunded_email, $refunded_count, $refunded_amount) {
    $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 insert_statistics_entry($conn, $match_id, $match_type, $match_title, $played_on, $email, $winnings, $winaddmsg, $refund_amount, $refund_reason) {
    $stmt = $conn->prepare("INSERT INTO statistics (match_id, type, match_title, played_on, email, winnings, winaddmsg, refund_amount, refund_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE winnings = winnings + VALUES(winnings), refund_amount = COALESCE(refund_amount, 0) + VALUES(refund_amount), winaddmsg = VALUES(winaddmsg), refund_reason = VALUES(refund_reason)");
    if (!$stmt) return false;
    $stmt->bind_param("issssdsds", $match_id, $match_type, $match_title, $played_on, $email, $winnings, $winaddmsg, $refund_amount, $refund_reason);
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    return $affected > 0;
}

function insert_user_announcement($conn, $email, $title, $image_link, $message) {
    $announce_date = date('Y-m-d');
    $announce_time = date('H:i:s');
    $stmt = $conn->prepare("INSERT INTO user_announcements (email, title, image_link, message, announce_date, announce_time, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("ssssss", $email, $title, $image_link, $message, $announce_date, $announce_time);
    $stmt->execute();
    $stmt->close();
}

function base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

function getAccessToken($jsonFilePath) {
    $credentials = json_decode(file_get_contents($jsonFilePath), true);
    if (!$credentials || !isset($credentials['private_key'])) return false;

    $clientEmail = $credentials['client_email'];
    $privateKey  = $credentials['private_key'];

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $payload = json_encode([
        'iss'   => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/cloud-platform',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ]);

    $unsignedJwt = base64url_encode($header) . "." . base64url_encode($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . base64url_encode($signature);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);
    return isset($responseData['access_token']) ? $responseData['access_token'] : false;
}

function sendFCMNotification($target_type, $target_value, $title, $body) {
    $serviceAccountFile = 'noti.json';
    if (!file_exists($serviceAccountFile)) return false;
    
    $accessToken = getAccessToken($serviceAccountFile);
    if (!$accessToken) return false;

    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    $projectId = $credentials['project_id'];
    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

    $notificationMap = [
        "title" => $title,
        "body"  => $body,
        "image" => "",
        "extra" => ""
    ];

    $messagePayload = [];
    if ($target_type === 'topic') {
        $messagePayload['topic'] = $target_value;
    } else {
        $messagePayload['token'] = $target_value;
    }
    $messagePayload['data'] = $notificationMap;
    $postData = json_encode(["message" => $messagePayload]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json; UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $httpCode == 200;
}

function get_match_table_and_data($conn, $match_id) {
    $match_id_str = (string)$match_id;
    $tables = ['freefire', 'match_schedule'];
    foreach ($tables as $tbl) {
        $stmt = $conn->prepare("SELECT * FROM `$tbl` WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param("s", $match_id_str);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                $stmt->close();
                return ['table' => $tbl, 'data' => $row];
            }
            $stmt->close();
        }
    }
    return null;
}

$action_req = $_POST['action'] ?? '';
$match_id_req = intval($_GET['match_id'] ?? ($_POST['match_id'] ?? 0));

if (!$match_id_req) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') respond_json("error", "ম্যাচের তথ্য পাওয়া যায়নি।");
    else die("<!DOCTYPE html><html><body style='font-family:system-ui;text-align:center;padding:50px;'><h2>Invalid Match ID</h2><a href='javascript:history.back()'>Go Back</a></body></html>");
}

$match_info = get_match_table_and_data($conn, $match_id_req);
if (!$match_info) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') respond_json("error", "ম্যাচটি ডাটাবেসে পাওয়া যায়নি।");
    else die("<!DOCTYPE html><html><body style='font-family:system-ui;text-align:center;padding:50px;'><h2>Match Not Found</h2><a href='javascript:history.back()'>Go Back</a></body></html>");
}

$match_table = $match_info['table'];
$match_data = $match_info['data'];
$match_id_str = (string)$match_id_req;
$entry_fee = (float)($match_data['entry_fee'] ?? 0);
$match_title = $match_data['match_title'] ?? 'Unknown Match';
$match_type = $match_data['match_type'] ?? 'freefire';
$played_on = $match_data['match_date'] ?? $match_data['match_time'] ?? $match_data['created_at'] ?? date('Y-m-d H:i:s');

$default_image = "https://skmesports.fun/ElitegoxUser//uploads/profile/fast.jpg";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action_req === 'single' || $action_req === 'all') {
        if (!$can_refund) {
            respond_json("error", "অনুমতি নেই: রিফান্ড করার অনুমতি আপনার নেই।");
        }
    }

    try {
        if ($action_req === 'single') {
            $joiner_id = intval($_POST['joiner_id'] ?? 0);
            $refund_reason = trim($_POST['refund_reason'] ?? '');
            $send_notification = isset($_POST['send_notification']) && $_POST['send_notification'] == '1';
            $image_link = trim($_POST['image_link'] ?? '');
            if ($image_link === '') $image_link = $default_image;
            if (!$joiner_id) respond_json("error", "ইউজারের আইডি পাওয়া যায়নি।");
            if ($refund_reason === '') respond_json("error", "রিফান্ডের কারণ দেওয়া আবশ্যক।");

            $conn->begin_transaction();

            $stmt = $conn->prepare("SELECT email, name, winning, total_kill FROM joiners WHERE id = ? AND match_id = ? LIMIT 1");
            $stmt->bind_param("is", $joiner_id, $match_id_str);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res->num_rows === 0) {
                $conn->rollback();
                respond_json("error", "ইউজার পাওয়া যায়নি।");
            }
            $row = $res->fetch_assoc();
            
            if ($row['winning'] > 0 || $row['total_kill'] > 0) {
                $conn->rollback();
                respond_json("error", "এই ইউজারকে ইতোমধ্যে কিল বা উইনিং দেওয়া হয়েছে, তাই রিফান্ড করা যাবে না।");
            }
            
            $target_email = $row['email'];
            $target_name = $row['name'];
            $stmt->close();

            $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE email = ?");
            $stmt->bind_param("ds", $entry_fee, $target_email);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("DELETE FROM joiners WHERE id = ?");
            $stmt->bind_param("i", $joiner_id);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("UPDATE `$match_table` SET total_joiner = GREATEST(total_joiner - 1, 0) WHERE id = ?");
            $stmt->bind_param("s", $match_id_str);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("UPDATE join_entry SET status = '+refunded' WHERE email = ? AND match_id = ?");
            $stmt->bind_param("ss", $target_email, $match_id_str);
            $stmt->execute();
            $stmt->close();

            log_refund($conn, $username, 'single', $match_id_req, $match_type, $match_title, $joiner_id, $target_email, 1, $entry_fee);
            
            $stat_ok = insert_statistics_entry($conn, $match_id_req, $match_type, $match_title, $played_on, $target_email, 0, '', $entry_fee, $refund_reason);
            if (!$stat_ok) {
                $conn->rollback();
                respond_json("error", "স্ট্যাটিস্টিকস সেভ করা যায়নি।");
            }

            $announceTitle = "রিফান্ড সম্পন্ন";
            $announceMessage = "আপনার \"{$match_title}\" ম্যাচের ৳{$entry_fee} রিফান্ড করা হয়েছে। কারণ: {$refund_reason}";
            insert_user_announcement($conn, $target_email, $announceTitle, $image_link, $announceMessage);

            $stmt = $conn->prepare("SELECT fcm_key FROM users WHERE email = ? LIMIT 1");
            $stmt->bind_param("s", $target_email);
            $stmt->execute();
            $fcm_res = $stmt->get_result();
            $fcm_token = ($fcm_row = $fcm_res->fetch_assoc()) ? $fcm_row['fcm_key'] : null;
            $stmt->close();

            $conn->commit();

            if ($fcm_token && $send_notification) {
                $notifyBody = "আপনার \"{$match_title}\" ম্যাচের ৳{$entry_fee} রিফান্ড করা হয়েছে। কারণ: {$refund_reason}";
                sendFCMNotification('token', $fcm_token, 'রিফান্ড সম্পন্ন', $notifyBody);
            }

            respond_json("success", "সফলভাবে রিফান্ড করা হয়েছে");

        } elseif ($action_req === 'all') {
            $refund_reason = trim($_POST['refund_reason'] ?? '');
            $send_notification = isset($_POST['send_notification']) && $_POST['send_notification'] == '1';
            $send_to_all_users = isset($_POST['send_to_all_users']) && $_POST['send_to_all_users'] == '1';
            $image_link = trim($_POST['image_link'] ?? '');
            if ($image_link === '') $image_link = $default_image;
            if ($refund_reason === '') respond_json("error", "রিফান্ডের কারণ দেওয়া আবশ্যক।");

            $conn->begin_transaction();

            $stmt = $conn->prepare("SELECT id, email, name FROM joiners WHERE match_id = ? AND winning = 0 AND total_kill = 0");
            $stmt->bind_param("s", $match_id_str);
            $stmt->execute();
            $res = $stmt->get_result();
            $joiners_to_refund = $res->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            if (count($joiners_to_refund) === 0) {
                $conn->rollback();
                respond_json("error", "এই ম্যাচে রিফান্ড করার মতো কোনো ইউজার নেই (হয়ত সবাইকে পুরস্কার দেওয়া হয়েছে)।");
            }

            $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_to_refund as $j) {
                $updUser->bind_param("ds", $entry_fee, $j['email']);
                $updUser->execute();

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

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

                log_refund($conn, $username, 'all', $match_id_req, $match_type, $match_title, $j['id'], $j['email'], 1, $entry_fee);
                
                $stat_ok = insert_statistics_entry($conn, $match_id_req, $match_type, $match_title, $played_on, $j['email'], 0, '', $entry_fee, $refund_reason);
                if (!$stat_ok) {
                    $conn->rollback();
                    respond_json("error", "স্ট্যাটিস্টিকস সেভ করা যায়নি।");
                }
                $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("is", $refunded_count, $match_id_str);
            $stmt->execute();
            $stmt->close();

            $announceTitle = "রিফান্ড সম্পন্ন";
            $announceMessage = "\"{$match_title}\" ম্যাচের সবার ৳{$entry_fee} রিফান্ড করা হয়েছে। কারণ: {$refund_reason}";
            foreach ($joiners_to_refund as $j) {
                insert_user_announcement($conn, $j['email'], $announceTitle, $image_link, $announceMessage);
            }

            $conn->commit();

            if ($send_notification) {
                $topicName = $send_to_all_users ? 'ttt' : ('match_' . $match_id_str);
                $notifyBody = "\"{$match_title}\" ম্যাচের সবার এন্ট্রি ফি (৳{$entry_fee}) রিফান্ড করা হয়েছে। কারণ: {$refund_reason}";
                sendFCMNotification('topic', $topicName, 'রিফান্ড সম্পন্ন', $notifyBody);
            }

            respond_json("success", "সফলভাবে {$refunded_count} জন ইউজারকে রিফান্ড করা হয়েছে।");

        } elseif ($action_req === 'add_kill_winning') {
            if (!$can_refund) {
                respond_json("error", "অনুমতি নেই।");
            }
            $joiner_id = intval($_POST['joiner_id'] ?? 0);
            $kill_count = intval($_POST['kill_count'] ?? 0);
            $winning_amount = intval($_POST['winning_amount'] ?? 0);
            $winaddmsg = trim($_POST['winaddmsg'] ?? '');
            $send_notification = isset($_POST['send_notification']) && $_POST['send_notification'] == '1';
            $image_link = trim($_POST['image_link'] ?? '');
            if ($image_link === '') $image_link = $default_image;
            if ($joiner_id <= 0 || $kill_count < 0 || $winning_amount < 0) {
                respond_json("error", "মান সঠিক নয়।");
            }

            $stmt = $conn->prepare("SELECT email, name, winning, total_kill FROM joiners WHERE id = ? AND match_id = ? LIMIT 1");
            $stmt->bind_param("is", $joiner_id, $match_id_str);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res->num_rows === 0) {
                respond_json("error", "ইউজার পাওয়া যায়নি।");
            }
            $row = $res->fetch_assoc();

            if ($row['winning'] > 0 || $row['total_kill'] > 0) {
                respond_json("error", "এই ইউজারকে ইতোমধ্যে পুরস্কার দেওয়া হয়েছে, দ্বিতীয়বার দেওয়া যাবে না।");
            }

            $target_email = $row['email'];
            $target_name = $row['name'];
            $stmt->close();

            $stmt = $conn->prepare("UPDATE users SET winning = winning + ?, total_win = total_win + ?, total_kill = total_kill + ? WHERE email = ?");
            $stmt->bind_param("iiis", $winning_amount, $winning_amount, $kill_count, $target_email);
            $stmt->execute();
            $stmt->close();

            $stmt = $conn->prepare("UPDATE joiners SET total_kill = ?, winning = ? WHERE id = ?");
            $stmt->bind_param("iii", $kill_count, $winning_amount, $joiner_id);
            $stmt->execute();
            $stmt->close();

            $status_check = $conn->prepare("SELECT status FROM users WHERE email = ?");
            $status_check->bind_param("s", $target_email);
            $status_check->execute();
            $status_res = $status_check->get_result();
            $user_status = '';
            if ($status_row = $status_res->fetch_assoc()) {
                $user_status = $status_row['status'] ?? '';
            }
            $status_check->close();

            $is_banned = in_array(strtolower(trim($user_status)), ['ban', 'banned']);
            if ($winning_amount > 0 && !$is_banned) {
                $stmt = $conn->prepare("UPDATE users SET total_paid = total_paid + ? WHERE email = ?");
                $stmt->bind_param("is", $winning_amount, $target_email);
                $stmt->execute();
                $stmt->close();
            }

            insert_statistics_entry($conn, $match_id_req, $match_type, $match_title, $played_on, $target_email, $winning_amount, $winaddmsg, 0, '');

            $announceTitle = "পুরস্কার যুক্ত হয়েছে";
            $announceMessage = "আপনি \"{$match_title}\" ম্যাচে ৳{$winning_amount} উইনিং এবং {$kill_count} কিল পেয়েছেন।";
            if (!empty($winaddmsg)) $announceMessage .= " বার্তা: {$winaddmsg}";
            insert_user_announcement($conn, $target_email, $announceTitle, $image_link, $announceMessage);

            if ($send_notification) {
                $stmt = $conn->prepare("SELECT fcm_key FROM users WHERE email = ? LIMIT 1");
                $stmt->bind_param("s", $target_email);
                $stmt->execute();
                $fcm_res = $stmt->get_result();
                $fcm_token = ($fcm_row = $fcm_res->fetch_assoc()) ? $fcm_row['fcm_key'] : null;
                $stmt->close();

                if ($fcm_token) {
                    $notifyBody = "আপনি \"{$match_title}\" ম্যাচে ৳{$winning_amount} উইনিং এবং {$kill_count} কিল পেয়েছেন।";
                    if (!empty($winaddmsg)) $notifyBody .= " {$winaddmsg}";
                    sendFCMNotification('token', $fcm_token, 'অভিনন্দন!', $notifyBody);
                }
            }

            respond_json("success", "সফলভাবে পুরস্কার দেওয়া হয়েছে");
        }
    } catch (Exception $e) {
        if ($conn->in_transaction) $conn->rollback();
        respond_json("error", "সিস্টেম এরর: " . $e->getMessage());
    }
}

$total_joiners = 0;
$c_stmt = $conn->prepare("SELECT COUNT(id) as c FROM joiners WHERE match_id = ?");
$c_stmt->bind_param("s", $match_id_str);
$c_stmt->execute();
$c_res = $c_stmt->get_result();
if ($c_row = $c_res->fetch_assoc()) {
    $total_joiners = $c_row['c'];
}
$c_stmt->close();

$joiners = [];
$stmt = $conn->prepare("SELECT id, name, winning, total_kill, mode, team_color, team_name, is_leader, email FROM joiners WHERE match_id = ? ORDER BY team_name ASC, is_leader DESC");
$stmt->bind_param("s", $match_id_str);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) {
    $joiners[] = $r;
}
$stmt->close();

$teams = [];
foreach ($joiners as $j) {
    $team = $j['team_name'] ?: 'No Team';
    if (!isset($teams[$team])) {
        $teams[$team] = [
            'team_name' => $team,
            'team_color' => $j['team_color'],
            'players' => []
        ];
    }
    $teams[$team]['players'][] = $j;
}

function e($str) { return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8'); }
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Manage Refunds</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --bg: #f8fafc; --surface: #ffffff; --primary: #3b82f6; --primary-hover: #2563eb;
            --danger: #ef4444; --warning: #f59e0b; --success: #10b981;
            --text-main: #1e293b; --text-muted: #64748b; --border: #e2e8f0;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.05);
            --radius-md: 12px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        body { background: var(--bg); color: var(--text-main); -webkit-font-smoothing: antialiased; }
        
        .topbar { background: var(--surface); padding: 16px 24px; display: flex; justify-content: space-between; align-items: center; box-shadow: var(--shadow-sm); position: sticky; top: 0; z-index: 100; border-bottom: 1px solid var(--border); }
        .brand { font-size: 18px; font-weight: 800; color: var(--primary); display: flex; align-items: center; gap: 8px; }
        
        .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
        
        .btn { padding: 10px 18px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: all 0.2s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; font-size: 14px; text-decoration: none; }
        .btn-primary { background: var(--primary); color: #fff; }
        .btn-primary:hover { background: var(--primary-hover); }
        .btn-danger { background: #fee2e2; color: #b91c1c; }
        .btn-danger:hover { background: #fca5a5; }
        .btn-outline { background: transparent; border: 1px solid var(--border); color: var(--text-main); }
        .btn-outline:hover { background: var(--bg); }
        
        .card { background: var(--surface); border-radius: var(--radius-md); padding: 24px; box-shadow: var(--shadow-md); margin-bottom: 24px; border: 1px solid var(--border); }
        
        .match-info { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
        .match-title { font-size: 20px; font-weight: 700; color: var(--text-main); margin-bottom: 8px; }
        .match-stats { display: flex; gap: 16px; color: var(--text-muted); font-size: 14px; font-weight: 500; flex-wrap: wrap; }
        .stat-badge { background: var(--bg); padding: 6px 12px; border-radius: 6px; border: 1px solid var(--border); display: flex; align-items: center; gap: 6px; }
        
        .search-container { position: relative; width: 100%; margin-bottom: 24px; }
        #searchInput { width: 100%; padding: 14px 20px 14px 44px; border: 1px solid var(--border); border-radius: var(--radius-md); font-size: 15px; outline: none; transition: border-color 0.2s; background: var(--surface); color: var(--text-main); box-shadow: var(--shadow-sm); }
        #searchInput:focus { border-color: var(--primary); }
        .search-icon { position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 16px; }

        .team-card { border: 2px solid var(--border); border-radius: var(--radius-md); margin-bottom: 24px; overflow: hidden; transition: opacity 0.3s; }
        .team-header { padding: 12px 20px; font-weight: 700; font-size: 16px; display: flex; align-items: center; gap: 10px; color: #fff; }
        .team-body { padding: 0; }
        .table-wrap { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; white-space: nowrap; }
        th, td { padding: 14px 16px; text-align: left; border-bottom: 1px solid var(--border); font-size: 14px; }
        th { background: #f1f5f9; color: var(--text-muted); font-weight: 600; text-transform: uppercase; font-size: 12px; letter-spacing: 0.5px; }
        tr:last-child td { border-bottom: none; }
        tr:hover td { background: #f8fafc; }

        .badge { padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 700; background: var(--border); text-transform: uppercase; }
        .badge-leader { background: #dbeafe; color: #1e40af; }
        
        .empty-state { text-align: center; padding: 40px 20px; color: var(--text-muted); }

        .toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; }
        .toast { background: var(--surface); color: var(--text-main); padding: 16px 20px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 12px; font-weight: 600; transform: translateX(120%); animation: slideIn 0.3s forwards; border-left: 4px solid var(--primary); }
        .toast.success { border-left-color: var(--success); }
        .toast.error { border-left-color: var(--danger); }
        @keyframes slideIn { to { transform: translateX(0); } }
        @keyframes fadeOut { to { opacity: 0; } }

        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 200; }
        .modal-overlay.active { display: flex; }
        .modal { background: var(--surface); border-radius: var(--radius-md); padding: 32px; width: 90%; max-width: 460px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.2); }
        .modal h3 { margin-bottom: 16px; font-size: 20px; }
        .modal label { display: block; margin-bottom: 6px; font-weight: 600; font-size: 14px; color: var(--text-muted); }
        .modal input, .modal textarea { width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; margin-bottom: 16px; font-size: 14px; font-family: inherit; resize: vertical; }
        .modal .checkbox-group { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; }
        .modal .checkbox-group input[type="checkbox"] { width: auto; margin: 0; }
        .modal .checkbox-group label { margin: 0; font-weight: 500; }
        .modal .modal-actions { display: flex; gap: 12px; justify-content: flex-end; }
        .modal .modal-actions .btn { min-width: 80px; }

        @media (max-width: 768px) {
            .match-info { flex-direction: column; align-items: flex-start; }
            .btn { width: 100%; }
        }
    </style>
</head>
<body>

<div class="topbar">
    <div class="brand"><i class="fa-solid fa-money-bill-transfer"></i> Refund Manager</div>
    <button class="btn btn-outline" onclick="history.back()"><i class="fa-solid fa-arrow-left"></i> Back</button>
</div>

<div class="container">
    <div class="card">
        <div class="match-info">
            <div>
                <div class="match-title"><?= e($match_title) ?> (ID: #<?= $match_id_req ?>)</div>
                <div class="match-stats">
                    <div class="stat-badge"><i class="fa-solid fa-users text-primary"></i> Total Joiners: <span id="joinerCountTxt"><?= $total_joiners ?></span></div>
                    <div class="stat-badge"><i class="fa-solid fa-coins text-warning"></i> Entry Fee: <?= $entry_fee ?> TK</div>
                    <div class="stat-badge"><i class="fa-solid fa-layer-group text-success"></i> Match: <?= e($match_type) ?></div>
                </div>
            </div>
            
            <?php if ($can_refund): ?>
                <div>
                    <button class="btn btn-danger" onclick="openRefundAllReasonModal()" <?= $total_joiners == 0 ? 'disabled style="opacity:0.5;cursor:not-allowed;"' : '' ?> id="btnRefundAll">
                        <i class="fa-solid fa-rotate-left"></i> Refund All (<?= $total_joiners ?>)
                    </button>
                </div>
            <?php else: ?>
                <div style="color:var(--danger); font-weight:600; font-size:14px;">
                    <i class="fa-solid fa-lock"></i> View Only (No Refund Permission)
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="search-container">
        <i class="fa-solid fa-magnifying-glass search-icon"></i>
        <input type="text" id="searchInput" placeholder="Search by Team Name or Player Name..." autocomplete="off">
    </div>

    <?php if (count($teams) > 0): ?>
        <?php foreach ($teams as $team): ?>
            <div class="team-card">
                <div class="team-header" style="background-color: <?= e($team['team_color'] ?: '#64748b') ?>;">
                    <i class="fa-solid fa-users"></i> <span class="team-name-text"><?= e($team['team_name']) ?></span>
                </div>
                <div class="team-body">
                    <div class="table-wrap">
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Player</th>
                                    <th>Email</th>
                                    <th>Mode</th>
                                    <th>Kills</th>
                                    <th>Winning</th>
                                    <th style="text-align:right;">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($team['players'] as $j): ?>
                                    <tr id="row-<?= $j['id'] ?>">
                                        <td style="font-weight:600; color:var(--primary);">#<?= $j['id'] ?></td>
                                        <td style="font-weight:600;" class="player-name-text">
                                            <?= e($j['name'] ?? 'N/A') ?>
                                            <?php if($j['is_leader'] == 1): ?>
                                                <span class="badge badge-leader"><i class="fa-solid fa-crown"></i> Leader</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="color:var(--text-muted);"><?= e($j['email']) ?></td>
                                        <td><span class="badge"><?= e($j['mode'] ?? 'N/A') ?></span></td>
                                        <td><?= (int)($j['total_kill'] ?? 0) ?></td>
                                        <td><?= (int)($j['winning'] ?? 0) ?></td>
                                        <td style="text-align:right;">
                                            <?php if ($can_refund): ?>
                                                <?php if ($j['total_kill'] > 0 || $j['winning'] > 0): ?>
                                                    <span style="color:var(--success); font-size:12px; font-weight:bold;"><i class="fa-solid fa-check"></i> Prize Given</span>
                                                <?php else: ?>
                                                    <button class="btn btn-danger" style="padding:6px 12px; font-size:12px;" onclick="openRefundSingleReasonModal(<?= $j['id'] ?>, '<?= e($j['email']) ?>')">
                                                        <i class="fa-solid fa-rotate-left"></i> Refund
                                                    </button>
                                                    <button class="btn btn-primary" style="padding:6px 12px; font-size:12px; margin-left:4px;" onclick="openKillWinningModal(<?= $j['id'] ?>, '<?= e($j['name'] ?? 'N/A') ?>')">
                                                        <i class="fa-solid fa-plus"></i> Add K/W
                                                    </button>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span style="color:var(--text-muted); font-size:12px;"><i class="fa-solid fa-ban"></i> No Permission</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="card empty-state">
            <i class="fa-solid fa-users-slash fa-3x" style="margin-bottom:16px; opacity:0.5;"></i>
            <h3>No Joiners Found</h3>
            <p>এই ম্যাচে কোনো ইউজার জয়েন করেনি।</p>
        </div>
    <?php endif; ?>
</div>

<div class="modal-overlay" id="refundReasonModal">
    <div class="modal">
        <h3><i class="fa-solid fa-file-pen"></i> Refund Reason</h3>
        <label>Please provide a reason for the refund</label>
        <textarea id="refundReasonInput" rows="3" placeholder="Enter reason..."></textarea>
        <div class="checkbox-group">
            <input type="checkbox" id="refundSendNotification" checked>
            <label for="refundSendNotification">Send notification</label>
        </div>
        <div id="refundAllUsersWrapper" style="display:block; margin-bottom:16px;">
            <div class="checkbox-group">
                <input type="checkbox" id="refundSendToAllUsers">
                <label for="refundSendToAllUsers">Send to All Users? (uncheck = only joiners)</label>
            </div>
        </div>
        <div id="refundImageLinkWrapper" style="display:block;">
            <label>Image Link (optional)</label>
            <input type="text" id="refundImageLink" placeholder="https://example.com/image.jpg">
        </div>
        <div class="modal-actions">
            <button class="btn btn-outline" onclick="closeRefundReasonModal()">Cancel</button>
            <button class="btn btn-primary" id="refundReasonSubmitBtn" onclick="submitRefundWithReason()">Proceed</button>
        </div>
    </div>
</div>

<div class="modal-overlay" id="kwModalOverlay">
    <div class="modal">
        <h3><i class="fa-solid fa-coins"></i> Add Kills & Winning</h3>
        <div style="margin-bottom:12px; font-size:14px;">
            <strong>Player:</strong> <span id="kwPlayerName"></span>
        </div>
        <label for="kwKillInput">Kills to add</label>
        <input type="number" id="kwKillInput" min="0" value="0" step="1">
        <label for="kwWinningInput">Winning to add</label>
        <input type="number" id="kwWinningInput" min="0" value="0" step="1">
        <label for="kwWinAddMsgInput">Prize Message (optional)</label>
        <input type="text" id="kwWinAddMsgInput" placeholder="e.g., Prize distribution message">
        <div class="checkbox-group">
            <input type="checkbox" id="kwSendNotification" checked>
            <label for="kwSendNotification">Send notification</label>
        </div>
        <div id="kwImageLinkWrapper" style="display:block;">
            <label>Image Link (optional)</label>
            <input type="text" id="kwImageLink" placeholder="https://example.com/image.jpg">
        </div>
        <div class="modal-actions">
            <button class="btn btn-outline" onclick="closeKillWinningModal()">Cancel</button>
            <button class="btn btn-primary" id="kwSubmitBtn" onclick="submitKillWinning()">Add</button>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
const matchId = <?= $match_id_req ?>;
let totalJoiners = <?= $total_joiners ?>;
let currentRefundType = null;
let currentRefundJoinerId = null;
let currentKwJoinerId = null;

document.getElementById('searchInput').addEventListener('input', function() {
    const query = this.value.toLowerCase().trim();
    const teamCards = document.querySelectorAll('.team-card');

    teamCards.forEach(card => {
        const teamName = card.querySelector('.team-name-text').textContent.toLowerCase();
        const playerRows = card.querySelectorAll('tbody tr');
        let matchFound = false;

        if (teamName.includes(query)) {
            matchFound = true;
        } else {
            playerRows.forEach(row => {
                const playerName = row.querySelector('.player-name-text').textContent.toLowerCase();
                if (playerName.includes(query)) {
                    matchFound = true;
                }
            });
        }

        if (matchFound || query === '') {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
});

function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `<i class="fa-solid ${type === 'success' ? 'fa-check-circle' : 'fa-circle-exclamation'}"></i> <span>${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => {
        toast.style.animation = 'fadeOut 0.3s forwards';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

function updateCount(decreaseBy) {
    totalJoiners = Math.max(0, totalJoiners - decreaseBy);
    document.getElementById('joinerCountTxt').innerText = totalJoiners;
    const btnAll = document.getElementById('btnRefundAll');
    if (btnAll) {
        btnAll.innerHTML = `<i class="fa-solid fa-rotate-left"></i> Refund All (${totalJoiners})`;
        if(totalJoiners === 0) {
            btnAll.disabled = true;
            btnAll.style.opacity = '0.5';
            btnAll.style.cursor = 'not-allowed';
        }
    }
}

function openRefundSingleReasonModal(joinerId, email) {
    currentRefundType = 'single';
    currentRefundJoinerId = joinerId;
    document.getElementById('refundReasonInput').value = 'অ্যাপটি সময় সমস্যা কারন এ ম্যাচ থেকে সবাই কো Refund করা হইছে';
    document.getElementById('refundSendNotification').checked = true;
    document.getElementById('refundImageLink').value = '<?= e($default_image) ?>';
    document.getElementById('refundAllUsersWrapper').style.display = 'none';
    document.getElementById('refundReasonModal').classList.add('active');
}

function openRefundAllReasonModal() {
    if(totalJoiners === 0) return;
    currentRefundType = 'all';
    document.getElementById('refundReasonInput').value = 'অ্যাপটি সময় সমস্যা কারন এ ম্যাচ থেকে সবাই কো Refund করা হইছে';
    document.getElementById('refundSendNotification').checked = true;
    document.getElementById('refundSendToAllUsers').checked = false;
    document.getElementById('refundImageLink').value = '<?= e($default_image) ?>';
    document.getElementById('refundAllUsersWrapper').style.display = 'block';
    document.getElementById('refundReasonModal').classList.add('active');
}

function closeRefundReasonModal() {
    document.getElementById('refundReasonModal').classList.remove('active');
    currentRefundType = null;
    currentRefundJoinerId = null;
}

async function submitRefundWithReason() {
    const reason = document.getElementById('refundReasonInput').value.trim();
    if (!reason) {
        showToast('রিফান্ডের কারণ দেওয়া আবশ্যক।', 'error');
        return;
    }
    const btn = document.getElementById('refundReasonSubmitBtn');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
    btn.disabled = true;

    const sendNotif = document.getElementById('refundSendNotification').checked ? '1' : '0';
    const imageLink = document.getElementById('refundImageLink').value.trim();
    const sendToAllUsers = document.getElementById('refundSendToAllUsers')?.checked ? '1' : '0';

    try {
        const data = {
            action: currentRefundType,
            match_id: matchId,
            refund_reason: reason,
            send_notification: sendNotif,
            image_link: imageLink
        };
        if (currentRefundType === 'single') {
            data.joiner_id = currentRefundJoinerId;
        } else if (currentRefundType === 'all') {
            data.send_to_all_users = sendToAllUsers;
        }
        const result = await sendRequest(data);
        if (result.success) {
            if (currentRefundType === 'single') {
                const row = document.getElementById(`row-${currentRefundJoinerId}`);
                if (row) {
                    row.style.opacity = '0.5';
                    setTimeout(() => row.remove(), 500);
                }
                updateCount(1);
            } else {
                setTimeout(() => window.location.reload(), 1000);
            }
        }
    } finally {
        btn.innerHTML = originalHTML;
        btn.disabled = false;
        closeRefundReasonModal();
    }
}

function openKillWinningModal(joinerId, name) {
    currentKwJoinerId = joinerId;
    document.getElementById('kwPlayerName').textContent = name;
    document.getElementById('kwKillInput').value = 0;
    document.getElementById('kwWinningInput').value = 0;
    document.getElementById('kwWinAddMsgInput').value = '';
    document.getElementById('kwSendNotification').checked = true;
    document.getElementById('kwImageLink').value = '<?= e($default_image) ?>';
    document.getElementById('kwModalOverlay').classList.add('active');
}

function closeKillWinningModal() {
    document.getElementById('kwModalOverlay').classList.remove('active');
}

async function submitKillWinning() {
    const killCount = parseInt(document.getElementById('kwKillInput').value) || 0;
    const winningAmount = parseInt(document.getElementById('kwWinningInput').value) || 0;
    const winaddmsg = document.getElementById('kwWinAddMsgInput').value.trim();
    if (killCount < 0 || winningAmount < 0) {
        showToast('মান নেগেটিভ হতে পারে না।', 'error');
        return;
    }
    if (killCount === 0 && winningAmount === 0) {
        showToast('দয়া করে শূন্যের চেয়ে বেশি মান দিন।', 'error');
        return;
    }
    const btn = document.getElementById('kwSubmitBtn');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Adding...';
    btn.disabled = true;

    const sendNotif = document.getElementById('kwSendNotification').checked ? '1' : '0';
    const imageLink = document.getElementById('kwImageLink').value.trim();

    const data = {
        action: 'add_kill_winning',
        match_id: matchId,
        joiner_id: currentKwJoinerId,
        kill_count: killCount,
        winning_amount: winningAmount,
        winaddmsg: winaddmsg,
        send_notification: sendNotif,
        image_link: imageLink
    };

    try {
        const result = await sendRequest(data);
        if (result.success) {
            showToast(result.message, 'success');
            closeKillWinningModal();
            setTimeout(() => location.reload(), 800);
        }
    } finally {
        btn.innerHTML = originalHTML;
        btn.disabled = false;
    }
}

async function sendRequest(data) {
    const formData = new FormData();
    for (const key in data) {
        formData.append(key, data[key]);
    }

    try {
        const response = await fetch(window.location.href, {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        if (result.status === 'success') {
            showToast(result.message, 'success');
            return { success: true, message: result.message };
        } else {
            showToast(result.message || 'কোনো একটি সমস্যা হয়েছে', 'error');
            return { success: false, message: result.message };
        }
    } catch (error) {
        showToast('নেটওয়ার্ক এরর', 'error');
        return { success: false, message: 'Network error' };
    }
}

document.getElementById('refundReasonModal').addEventListener('click', function(e) {
    if (e.target === this) closeRefundReasonModal();
});
document.getElementById('kwModalOverlay').addEventListener('click', function(e) {
    if (e.target === this) closeKillWinningModal();
});
</script>

</body>
</html>