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

if (!isset($conn) && isset($con)) {
    $conn = $con;
}
$conn->set_charset("utf8mb4");

$admin_username = trim($_POST['admin_username'] ?? '');
$admin_password = trim($_POST['admin_password'] ?? '');

if (empty($admin_username) || empty($admin_password)) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Admin Username and Password required!"]);
    exit;
}

$admin_password_md5 = md5($admin_password);
$auth_valid = false;

$stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND (password=? OR password=?) LIMIT 1");
if ($stmt) {
    $stmt->bind_param("sss", $admin_username, $admin_password, $admin_password_md5);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        $auth_valid = true;
    }
    $stmt->close();
}

if (!$auth_valid) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied! Admin Credentials Invalid."]);
    exit;
}

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

if ($action == 'get_categories') {
    $categories = [];
    $cat_result = $conn->query("SELECT title FROM category");
    if ($cat_result) {
        while ($row = $cat_result->fetch_assoc()) {
            $categories[] = $row['title'];
        }
    }
    echo json_encode(["status" => "success", "categories" => $categories]);
    exit;
}

if ($action == 'get_moderator') {
    $mod_username = trim($_POST['mod_username'] ?? '');
    $stmt = $conn->prepare("SELECT * FROM modarator_permissions WHERE username=? LIMIT 1");
    $stmt->bind_param("s", $mod_username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $data = $result->fetch_assoc();
        echo json_encode(["status" => "success", "exists" => true, "data" => $data]);
    } else {
        echo json_encode(["status" => "success", "exists" => false]);
    }
    $stmt->close();
    exit;
}

if ($action == 'save_moderator') {
    $mod_username = trim($_POST['mod_username'] ?? '');
    $mod_password = trim($_POST['mod_password'] ?? '');

    if (empty($mod_username) || empty($mod_password)) {
        echo json_encode(["status" => "error", "message" => "Moderator Username and Password required"]);
        exit;
    }

    $core_columns = ['users_control', 'money_history', 'database_editing', 'notifications', 'match_rules', 'add_winnings', 'refund', 'match_delete', 'match_editing', 'match_ongoing_results'];

    $form_permissions = [];
    foreach ($core_columns as $col) {
        $form_permissions[$col] = (isset($_POST[$col]) && $_POST[$col] === 'Yes') ? 'Yes' : 'No';
    }

    $extra_json_data = [];
    if (isset($_POST['dynamic_permissions']) && is_array($_POST['dynamic_permissions'])) {
        foreach ($_POST['dynamic_permissions'] as $cat => $perms) {
            $extra_json_data[$cat] = [
                'Add' => (isset($perms['Add']) && $perms['Add'] === 'Yes') ? 'Yes' : 'No',
                'Edit' => (isset($perms['Edit']) && $perms['Edit'] === 'Yes') ? 'Yes' : 'No',
                'Delete' => (isset($perms['Delete']) && $perms['Delete'] === 'Yes') ? 'Yes' : 'No'
            ];
        }
    }

    $extra_keys = ['match_category_permissions', 'bonus_management', 'withdrawals', 'order_fulfillment', 'policy_rules'];
    foreach ($extra_keys as $key) {
        $extra_json_data[$key] = (isset($_POST['extra_perms'][$key]) && $_POST['extra_perms'][$key] === 'Yes') ? 'Yes' : 'No';
    }

    $extra_json_string = !empty($extra_json_data) ? json_encode($extra_json_data, JSON_UNESCAPED_UNICODE) : null;

    $check_stmt = $conn->prepare("SELECT id FROM modarator_permissions WHERE username=? LIMIT 1");
    $check_stmt->bind_param("s", $mod_username);
    $check_stmt->execute();
    $user_exists = $check_stmt->get_result()->num_rows > 0;
    $check_stmt->close();

    if ($user_exists) {
        $sql = "UPDATE modarator_permissions SET password=?, users_control=?, money_history=?, database_editing=?, notifications=?, match_rules=?, add_winnings=?, refund=?, match_delete=?, match_editing=?, match_ongoing_results=?, extra_json=? WHERE username=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssssssssss", $mod_password, $form_permissions['users_control'], $form_permissions['money_history'], $form_permissions['database_editing'], $form_permissions['notifications'], $form_permissions['match_rules'], $form_permissions['add_winnings'], $form_permissions['refund'], $form_permissions['match_delete'], $form_permissions['match_editing'], $form_permissions['match_ongoing_results'], $extra_json_string, $mod_username);
        $msg = "Moderator permissions updated successfully";
    } else {
        $sql = "INSERT INTO modarator_permissions (username, password, users_control, money_history, database_editing, notifications, match_rules, add_winnings, refund, match_delete, match_editing, match_ongoing_results, extra_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssssssssss", $mod_username, $mod_password, $form_permissions['users_control'], $form_permissions['money_history'], $form_permissions['database_editing'], $form_permissions['notifications'], $form_permissions['match_rules'], $form_permissions['add_winnings'], $form_permissions['refund'], $form_permissions['match_delete'], $form_permissions['match_editing'], $form_permissions['match_ongoing_results'], $extra_json_string);
        $msg = "Moderator added successfully";
    }

    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => $msg]);
    } else {
        echo json_encode(["status" => "error", "message" => $stmt->error]);
    }
    $stmt->close();
} else {
    echo json_encode(["status" => "error", "message" => "Invalid action"]);
}
$conn->close();
?>
