<?php
require_once "../../includes/db.php";
header('Content-Type: application/json');
session_start();

$coid = $_SESSION['co_id'];

$perm_limit  = $_GET['perm_limit'] ?? 15;
$perm_offset = $_GET['perm_offset'] ?? 0;
$pm_user     = $_GET['pm_user'] ?? '';

$stmt = $pdo->prepare("
    SELECT 
        p.pm_id,
        p.user_id,
        CONCAT(u.firstname,' ', u.secondname) AS name,
        c.acc_name,
        p.pm_acc_categ,

        CASE
            WHEN p.menu_access='accounts' THEN 'Accounts'
            WHEN p.menu_access='inventory' THEN 'Inventory'
            WHEN p.menu_access='customers' THEN 'Customers'
            WHEN p.menu_access='suppliers' THEN 'Suppliers'
            WHEN p.menu_access='products' THEN 'Products'
            WHEN p.menu_access='permissions' THEN 'Permissions'
            WHEN p.menu_access='accounts_lists' THEN 'Charts of Accounts'
            WHEN p.menu_access='cash_adj' THEN 'Cash Adjustment'
        END AS menu,

        CASE
            WHEN p.pm_acc_lvl = 0 THEN 'View only'
            WHEN p.pm_acc_lvl = 1 THEN 'View & Confirm'
            WHEN p.pm_acc_lvl = 2 THEN 'View & Transfer to Account'
            WHEN p.pm_acc_lvl = 3 THEN 'View & Transfer from Account'
            WHEN p.pm_acc_lvl = 4 THEN 'View,Transfer to & from Account'
            WHEN p.pm_acc_lvl = 5 THEN 'View,confirm,Transfer to & from Account'
            WHEN p.pm_acc_lvl = 6 THEN 'View & Approve Transactions'
            WHEN p.pm_acc_lvl = 7 THEN 'All access'
            WHEN p.pm_acc_lvl = 11 THEN 'Create'
        END AS permission_level

    FROM permissions p

    JOIN users u 
        ON p.user_id = u.id

    LEFT JOIN accounts c 
        ON c.id = p.pm_acc_id

    WHERE p.co_id = :coid

    AND (
        CONCAT(u.firstname,' ',u.secondname) LIKE :pm_user
        OR c.acc_name LIKE :pm_user
        OR p.pm_acc_categ LIKE :pm_user
        OR p.menu_access LIKE :pm_user
    )

    ORDER BY p.pm_id ASC

    LIMIT :perm_limit OFFSET :perm_offset
");

$search = "%".$pm_user."%";

$stmt->bindValue(':coid', $coid, PDO::PARAM_INT);
$stmt->bindValue(':pm_user', $search, PDO::PARAM_STR);
$stmt->bindValue(':perm_limit', (int)$perm_limit, PDO::PARAM_INT);
$stmt->bindValue(':perm_offset', (int)$perm_offset, PDO::PARAM_INT);

$stmt->execute();

echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
exit;