<?php
header('Content-Type: application/json');
include 'config.php';

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

/* ================= MODARATOR LOGIN ================= */
if ($type === 'login') {

    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    $stmt = $conn->prepare("SELECT username, password FROM modarator WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows > 0) {
        $m = $res->fetch_assoc();

        if ($m['password'] === $password) {
            echo json_encode([
                "status" => "success",
                "message" => "Login Success",
                "username" => $m['username']
            ]);
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid Password"]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "No Modarator Found"]);
    }
    $stmt->close();
}

/* ================= ADD MODARATOR ================= */
elseif ($type == 'add') {

    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if ($username == '' || $password == '') {
        echo "Username or Password empty";
        exit;
    }

    $stmt = $conn->prepare(
        "INSERT INTO modarator (username, password, type) VALUES (?, ?, 'modarator')"
    );
    $stmt->bind_param("ss", $username, $password);

    if ($stmt->execute()) {
        $conn->query("INSERT INTO modarator_permissions (username) VALUES ('$username')");
        echo "Modarator Added Successfully";
    } else {
        echo "Insert failed";
    }
    $stmt->close();
}

/* ================= LIST MODARATOR ================= */
elseif ($type == 'list') {

    $res = $conn->query("SELECT * FROM modarator ORDER BY id ASC");
    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
}

/* ================= DELETE MODARATOR ================= */
elseif ($type == 'delete') {

    $id = $_POST['id'] ?? '';
    if ($id == '') {
        echo "ID required";
        exit;
    }

    $get = $conn->query("SELECT username FROM modarator WHERE id='$id'");
    if ($get->num_rows == 0) {
        echo "Modarator not found";
        exit;
    }

    $u = $get->fetch_assoc()['username'];
    $conn->query("DELETE FROM modarator WHERE id='$id'");
    $conn->query("DELETE FROM modarator_permissions WHERE username='$u'");
    echo "Modarator Deleted Successfully";
}

/* ================= CHANGE USERNAME & PASSWORD ================= */
elseif ($type == 'change') {

    $id = $_POST['id'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if ($id == '' || $username == '' || $password == '') {
        echo "Missing data";
        exit;
    }

    $old = $conn->query("SELECT username FROM modarator WHERE id='$id'");
    if ($old->num_rows == 0) {
        echo "Modarator not found";
        exit;
    }

    $oldUsername = $old->fetch_assoc()['username'];
    $conn->query("UPDATE modarator SET username='$username', password='$password' WHERE id='$id'");
    $conn->query("UPDATE modarator_permissions SET username='$username' WHERE username='$oldUsername'");
    echo "Modarator Updated Successfully";
}

/* ================= SAVE PERMISSIONS ================= */
elseif ($type == 'save_permissions') {

    $username = $_POST['username'] ?? '';
    if ($username == '') {
        echo "Username required";
        exit;
    }

    $fields = [
        'users_control','money_history','database_editing',
        'br_matches','survival_matches','clash_squad_matches','cs_2v2_matches',
        'lone_wolf','lose_to_win','ludo_matches','free_matches',
        'notifications','match_rules','match_images',
        'add_winnings','refund','match_delete','match_editing','match_ongoing_results',

        // ===== ADD MATCH PERMISSIONS =====
        'br_matches_add',
        'survival_matches_add',
        'clash_squad_matches_add',
        'cs_2v2_matches_add',
        'lone_wolf_add',
        'lose_to_win_add',
        'ludo_matches_add',
        'free_matches_add'
    ];

    $set = [];
    foreach ($fields as $f) {
        $val = $_POST[$f] ?? 'No';
        $set[] = "$f='$val'";
    }

    $sql = "UPDATE modarator_permissions SET ".implode(',', $set)." WHERE username='$username'";
    $conn->query($sql);
    echo "Permissions Saved Successfully";
}

/* ================= GET PERMISSIONS ================= */
elseif ($type == 'get_permissions') {

    $username = $_POST['username'] ?? '';
    $res = $conn->query("SELECT * FROM modarator_permissions WHERE username='$username'");

    if ($res->num_rows == 0) {
        echo json_encode([]);
    } else {
        echo json_encode($res->fetch_assoc(), JSON_PRETTY_PRINT);
    }
}

else {
    echo "Invalid type";
}

$conn->close();
?>