<?php
include 'config.php';
header('Content-Type: application/json');
$conn->set_charset("utf8mb4");

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

// ১. মডারেটর অথেনটিকেশন (admin টেবিলের বদলে modarator_permissions ব্যবহার করা হলো)
$auth_stmt = $conn->prepare("SELECT extra_json FROM modarator_permissions WHERE username=? AND password=? LIMIT 1");
$auth_stmt->bind_param("ss", $admin_username, $admin_password);
$auth_stmt->execute();
$auth_result = $auth_stmt->get_result();

if ($auth_result->num_rows == 0) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied"]);
    exit;
}
$mod_data = $auth_result->fetch_assoc();
$auth_stmt->close();

// ২. JSON পারমিশন ডিকোড
$extra_perms = json_decode($mod_data['extra_json'] ?? '{}', true);
if (!is_array($extra_perms)) $extra_perms = [];

$allowed_cats = [];
foreach ($extra_perms as $cat => $perms) {
    if (($perms['Add'] ?? 'No') == 'Yes' || ($perms['Edit'] ?? 'No') == 'Yes' || ($perms['Delete'] ?? 'No') == 'Yes') {
        $allowed_cats[] = $cat; // যেসব ক্যাটাগরিতে অন্তত ১টি পারমিশন আছে
    }
}

$action = $_POST['action'] ?? '';

if ($action == 'list') {
    // যদি কোনো ক্যাটাগরিরই অ্যাক্সেস না থাকে, তাহলে ফাঁকা রিটার্ন করবে
    if (empty($allowed_cats)) {
        echo json_encode(["status" => "success", "matches" => [], "total" => 0, "total_pages" => 0]);
        exit;
    }

    $search = isset($_POST['search']) ? trim($_POST['search']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $limit = isset($_POST['show']) ? intval($_POST['show']) : 20;
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    if ($limit < 1) $limit = 1;
    if ($page < 1) $page = 1;
    $offset = ($page - 1) * $limit;

    $where = [];
    $params = [];
    $types = "";

    // সিকিউরিটি: শুধুমাত্র Allowed Categories এর ডাটাই ডাটাবেজ থেকে আনবে
    $cat_placeholders = implode(',', array_fill(0, count($allowed_cats), '?'));
    $where[] = "match_type IN ($cat_placeholders)";
    foreach($allowed_cats as $c) {
        $params[] = $c;
        $types .= "s";
    }

    // সার্চ ফিল্টার
    if (!empty($search)) {
        $where[] = "(match_title LIKE ? OR match_type LIKE ? OR play_map LIKE ? OR version LIKE ? OR entry_type LIKE ?)";
        $term = "%" . $search . "%";
        $params = array_merge($params, [$term, $term, $term, $term, $term]);
        $types .= "sssss";
    }

    // ড্রপডাউন ক্যাটাগরি ফিল্টার
    if (!empty($category) && in_array($category, $allowed_cats)) {
        $where[] = "match_type = ?";
        $params[] = $category;
        $types .= "s";
    }

    $where_clause = "WHERE " . implode(" AND ", $where);

    // কাউন্ট কোয়েরি
    $count_sql = "SELECT COUNT(*) AS total FROM freefire $where_clause";
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($params)) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $count_res = $count_stmt->get_result();
    $total_row = $count_res->fetch_assoc();
    $total = (int)$total_row['total'];
    $count_stmt->close();

    // ডাটা কোয়েরি
    $sql = "SELECT * FROM freefire $where_clause ORDER BY id DESC LIMIT ? OFFSET ?";
    $stmt = $conn->prepare($sql);
    $params[] = $limit;
    $params[] = $offset;
    $types .= "ii";
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    $stmt->close();

    $total_pages = ($total > 0) ? ceil($total / $limit) : 1;
    echo json_encode([
        "status" => "success",
        "matches" => $data,
        "total" => $total,
        "current_page" => $page,
        "per_page" => $limit,
        "total_pages" => $total_pages
    ]);

} elseif ($action == 'add' || $action == 'update') {
    $id = intval($_POST['id'] ?? 0);
    $match_type = $_POST['match_type'] ?? '';
    
    // Backend API Security Check
    $req_perm = ($action == 'add') ? 'Add' : 'Edit';
    if (!isset($extra_perms[$match_type][$req_perm]) || $extra_perms[$match_type][$req_perm] !== 'Yes') {
        echo json_encode(["status" => "error", "message" => "Permission Denied! এই ক্যাটাগরিতে $req_perm করার অধিকার আপনার নেই।"]);
        exit;
    }
    
    $fields = [
        'match_title', 'match_time', 'total_prize', 'per_kill', 'entry_type',
        'entry_fee', 'match_type', 'version', 'play_map', 'registration',
        'prize_details', 'room_id', 'room_pass', 'total_player', 'total_joiner',
        'match_result', 'timer', 'join_type', 'image_link', 'locked',
        'locked_type', 'player_name_change', 'start_time', 'status'
    ];
    
    $values = [];
    $set_parts = [];
    $types = "";
    
    foreach ($fields as $f) {
        $val = $_POST[$f] ?? '';
        
        if ($f == 'locked' || $f == 'player_name_change') {
            $val = ($val === 'true' || $val === '1' || $val === 1) ? 1 : 0;
        }
        if (in_array($f, ['total_prize', 'per_kill', 'entry_fee', 'total_player', 'total_joiner', 'timer'])) {
            $val = intval($val);
        }
        if ($f == 'image_link' && empty(trim($val))) {
            $val = 'https://via.placeholder.com/300x200/2c2c2e/ffffff?text=FreeFire';
        }
        if (in_array($f, ['room_id', 'room_pass']) && empty(trim($val))) {
            $val = 'NO';
        }
        if ($f == 'match_result' && empty(trim($val))) {
            $val = 'NO';
        }
        if ($f == 'registration' && empty(trim($val))) {
            $val = 'Open';
        }
        if ($f == 'status' && empty(trim($val))) {
            $val = 'Pending';
        }
        
        $values[] = $val;
        $set_parts[] = "$f = ?";
        $types .= "s";
    }
    
    if ($action == 'add') {
        $sql = "INSERT INTO freefire (" . implode(",", $fields) . ") VALUES (" . implode(",", array_fill(0, count($fields), "?")) . ")";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$values);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Match added successfully", "id" => $stmt->insert_id]);
        } else {
            echo json_encode(["status" => "error", "message" => $stmt->error]);
        }
        $stmt->close();
        
    } else {
        if ($id <= 0) {
            echo json_encode(["status" => "error", "message" => "Invalid ID"]);
            exit;
        }
        $values[] = $id;
        $types .= "i";
        $sql = "UPDATE freefire SET " . implode(", ", $set_parts) . " WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$values);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Match updated successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => $stmt->error]);
        }
        $stmt->close();
    }

} elseif ($action == 'delete') {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
        exit;
    }
    
    // Backend Delete Security Check
    $cat_stmt = $conn->prepare("SELECT match_type FROM freefire WHERE id=?");
    $cat_stmt->bind_param("i", $id);
    $cat_stmt->execute();
    $cat_res = $cat_stmt->get_result();
    if($cat_res->num_rows > 0){
        $match_type = $cat_res->fetch_assoc()['match_type'];
        if (!isset($extra_perms[$match_type]['Delete']) || $extra_perms[$match_type]['Delete'] !== 'Yes') {
            echo json_encode(["status" => "error", "message" => "Permission Denied! এই ক্যাটাগরিতে Delete করার অধিকার আপনার নেই।"]);
            exit;
        }
    }
    $cat_stmt->close();

    $stmt = $conn->prepare("DELETE FROM freefire WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Match deleted successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => $stmt->error]);
    }
    $stmt->close();

} elseif ($action == 'categories') {
    $stmt = $conn->prepare("SELECT id, title FROM category ORDER BY title");
    $stmt->execute();
    $result = $stmt->get_result();
    $cats = [];
    while ($row = $result->fetch_assoc()) {
        $cats[] = $row;
    }
    $stmt->close();
    echo json_encode(["status" => "success", "categories" => $cats]);

} else {
    echo json_encode(["status" => "error", "message" => "Invalid action"]);
}

$conn->close();
?>