<?php
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');

include 'config.php';
$conn->set_charset("utf8mb4");
session_start();

function respond($status, $message, $data = [], $code = 200) {
    http_response_code($code);
    echo json_encode([
        "status"  => $status,
        "message" => $message,
        "data"    => $data
    ]);
    exit;
}

function logged_in() {
    return isset($_SESSION['admin_logged_in']) &&
           $_SESSION['admin_logged_in'] === true &&
           isset($_SESSION['admin_user']) &&
           isset($_SESSION['admin_pass']);
}

function get_permission_row($conn, $username) {
    $stmt = $conn->prepare("SELECT * FROM modarator_permissions WHERE username = ? LIMIT 1");
    if (!$stmt) return null;

    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return $row;
}

function get_allowed_categories($row) {
    $extra_json_str = $row['extra_json'] ?? '{}';
    $extra_perms = json_decode($extra_json_str, true);
    if (!is_array($extra_perms)) $extra_perms = [];

    $allowed = [];
    foreach ($extra_perms as $category_name => $perms) {
        $add = (isset($perms['Add']) && $perms['Add'] === 'Yes');
        $edit = (isset($perms['Edit']) && $perms['Edit'] === 'Yes');
        $delete = (isset($perms['Delete']) && $perms['Delete'] === 'Yes');

        if ($add || $edit || $delete) {
            $allowed[$category_name] = [
                'Add' => $add ? 'Yes' : 'No',
                'Edit' => $edit ? 'Yes' : 'No',
                'Delete' => $delete ? 'Yes' : 'No'
            ];
        }
    }

    return $allowed;
}

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

if ($action === 'login') {
    $admin_username = trim($_POST['admin_username'] ?? '');
    $admin_password = trim($_POST['admin_password'] ?? '');

    if ($admin_username === '' || $admin_password === '') {
        respond('error', 'Username/password required.', [], 400);
    }

    $stmt = $conn->prepare("SELECT * FROM admin WHERE username = ? LIMIT 1");
    if (!$stmt) {
        respond('error', 'Database error.', [], 500);
    }

    $stmt->bind_param("s", $admin_username);
    $stmt->execute();
    $res = $stmt->get_result();
    $admin = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!$admin) {
        respond('error', 'Invalid Credentials!', [], 401);
    }

    $dbPass = (string)($admin['password'] ?? '');
    $ok = password_verify($admin_password, $dbPass) || hash_equals($dbPass, $admin_password);

    if (!$ok) {
        respond('error', 'Invalid Credentials!', [], 401);
    }

    session_regenerate_id(true);
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_user'] = $admin_username;
    $_SESSION['admin_pass'] = $admin_password;

    respond('success', 'Login successful.');
}

if (!logged_in()) {
    respond('error', 'Access Denied. Please login.', [], 403);
}

$admin_user = $_SESSION['admin_user'];
$admin_pass  = $_SESSION['admin_pass'];

$row = get_permission_row($conn, $admin_user);
if (!$row) {
    session_unset();
    session_destroy();
    respond('error', 'Session expired.', [], 403);
}

$can_match_editing = strtolower(trim((string)($row['match_editing'] ?? 'no'))) === 'yes';
if (!$can_match_editing) {
    respond('error', 'Access denied.', [], 403);
}

$allowed_categories = get_allowed_categories($row);

if ($action === 'get_categories') {
    $sql = "SELECT id, title FROM category ORDER BY id DESC";
    $res = $conn->query($sql);

    $data = [];
    if ($res) {
        while ($cat = $res->fetch_assoc()) {
            $title = $cat['title'];
            if (isset($allowed_categories[$title])) {
                $data[] = [
                    'id' => (int)$cat['id'],
                    'match_type' => $title
                ];
            }
        }
    }

    respond('success', 'Loaded.', $data);
}

if ($action === 'get_rule') {
    $category_id = (int)($_POST['category_id'] ?? 0);

    if ($category_id <= 0) {
        respond('error', 'Invalid category.', [], 400);
    }

    $stmt = $conn->prepare("SELECT id, title FROM category WHERE id = ? LIMIT 1");
    if (!$stmt) {
        respond('error', 'Database error.', [], 500);
    }

    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $category = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!$category) {
        respond('error', 'Category not found.', [], 404);
    }

    $match_type = $category['title'];

    if (!isset($allowed_categories[$match_type])) {
        respond('error', 'Permission denied.', [], 403);
    }

    $stmt = $conn->prepare("SELECT id, match_type, rules FROM match_rules WHERE match_type = ? LIMIT 1");
    if (!$stmt) {
        respond('error', 'Database error.', [], 500);
    }

    $stmt->bind_param("s", $match_type);
    $stmt->execute();
    $res = $stmt->get_result();
    $rule = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if ($rule) {
        respond('success', 'Loaded.', [
            'exists' => true,
            'id' => (int)$rule['id'],
            'match_type' => $rule['match_type'],
            'rules' => $rule['rules']
        ]);
    }

    respond('success', 'Loaded.', [
        'exists' => false,
        'id' => 0,
        'match_type' => $match_type,
        'rules' => ''
    ]);
}

if ($action === 'save_rule') {
    $category_id = (int)($_POST['category_id'] ?? 0);
    $rules = trim($_POST['rules'] ?? '');

    if ($category_id <= 0) {
        respond('error', 'Please select category.', [], 400);
    }

    if ($rules === '') {
        respond('error', 'Rules cannot be empty.', [], 400);
    }

    $stmt = $conn->prepare("SELECT id, title FROM category WHERE id = ? LIMIT 1");
    if (!$stmt) {
        respond('error', 'Database error.', [], 500);
    }

    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $category = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!$category) {
        respond('error', 'Category not found.', [], 404);
    }

    $match_type = $category['title'];

    if (!isset($allowed_categories[$match_type])) {
        respond('error', 'Permission denied.', [], 403);
    }

    $check = $conn->prepare("SELECT id FROM match_rules WHERE match_type = ? LIMIT 1");
    if (!$check) {
        respond('error', 'Database error.', [], 500);
    }

    $check->bind_param("s", $match_type);
    $check->execute();
    $checkRes = $check->get_result();

    if ($checkRes && $checkRes->num_rows > 0) {
        $upd = $conn->prepare("UPDATE match_rules SET rules = ? WHERE match_type = ?");
        if (!$upd) {
            $check->close();
            respond('error', 'Database error.', [], 500);
        }

        $upd->bind_param("ss", $rules, $match_type);
        if ($upd->execute()) {
            $upd->close();
            $check->close();
            respond('success', 'Rules updated successfully.');
        }

        $err = $upd->error;
        $upd->close();
        $check->close();
        respond('error', $err ?: 'Update failed.', [], 500);
    }

    $ins = $conn->prepare("INSERT INTO match_rules (match_type, rules) VALUES (?, ?)");
    if (!$ins) {
        $check->close();
        respond('error', 'Database error.', [], 500);
    }

    $ins->bind_param("ss", $match_type, $rules);
    if ($ins->execute()) {
        $ins->close();
        $check->close();
        respond('success', 'Rules added successfully.');
    }

    $err = $ins->error;
    $ins->close();
    $check->close();
    respond('error', $err ?: 'Insert failed.', [], 500);
}

respond('error', 'Invalid action.', [], 400);