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

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

$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');

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

$md5_pass = md5($password);
$has_permission = false;

// ১. প্রথমে Admin চেক করা হচ্ছে (অ্যাডমিন হলে সব পারমিশন পাবে)
$admin_stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND (password=? OR password=?) LIMIT 1");
if ($admin_stmt) {
    $admin_stmt->bind_param("sss", $username, $password, $md5_pass);
    $admin_stmt->execute();
    if ($admin_stmt->get_result()->num_rows > 0) {
        $has_permission = true;
    }
    $admin_stmt->close();
}

// ২. অ্যাডমিন না হলে Moderator এর extra_json পারমিশন চেক করা হচ্ছে
if (!$has_permission) {
    $mod_stmt = $conn->prepare("SELECT extra_json FROM modarator_permissions WHERE username=? AND (password=? OR password=?) LIMIT 1");
    if ($mod_stmt) {
        $mod_stmt->bind_param("sss", $username, $password, $md5_pass);
        $mod_stmt->execute();
        $mod_res = $mod_stmt->get_result();
        if ($mod_res->num_rows > 0) {
            $mod_data = $mod_res->fetch_assoc();
            $extra_json = json_decode($mod_data['extra_json'], true);
            
            // Match Category Permissions চেক করা
            if (isset($extra_json['match_category_permissions']) && $extra_json['match_category_permissions'] === 'Yes') {
                $has_permission = true;
            }
        }
        $mod_stmt->close();
    }
}

if (!$has_permission) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied! Match Category Permission is required."]);
    exit;
}

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

if ($action == 'list') {
    $search = trim($_POST['search'] ?? '');
    $sql = "SELECT * FROM category ORDER BY id DESC";
    
    if (!empty($search)) {
        $search = "%" . $search . "%";
        $sql = "SELECT * FROM category WHERE title LIKE ? ORDER BY id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $search);
    } else {
        $stmt = $conn->prepare($sql);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    $stmt->close();
    
    echo json_encode(["status" => "success", "categories" => $data]);

} elseif ($action == 'add') {
    $title = trim($_POST['title'] ?? '');
    $image_link = trim($_POST['image_link'] ?? '');
    
    $stmt = $conn->prepare("INSERT INTO category (title, image_link) VALUES (?, ?)");
    $stmt->bind_param("ss", $title, $image_link);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "সফলভাবে যোগ করা হয়েছে", "id" => $stmt->insert_id]);
    } else {
        echo json_encode(["status" => "error", "message" => "ডাটাবেজ এরর"]);
    }
    $stmt->close();

} elseif ($action == 'update') {
    $id = intval($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $image_link = trim($_POST['image_link'] ?? '');
    
    if ($id <= 0) {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
        exit;
    }
    
    $stmt = $conn->prepare("UPDATE category SET title=?, image_link=? WHERE id=?");
    $stmt->bind_param("ssi", $title, $image_link, $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "সফলভাবে আপডেট করা হয়েছে"]);
    } else {
        echo json_encode(["status" => "error", "message" => "ডাটাবেজ এরর"]);
    }
    $stmt->close();

} elseif ($action == 'delete') {
    $id = intval($_POST['id'] ?? 0);
    
    if ($id <= 0) {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
        exit;
    }
    
    $stmt = $conn->prepare("DELETE FROM category WHERE id=?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "সফলভাবে ডিলিট করা হয়েছে"]);
    } else {
        echo json_encode(["status" => "error", "message" => "ডাটাবেজ এরর"]);
    }
    $stmt->close();

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

$conn->close();
?>
