<?php
ini_set('session.cookie_secure', 1);
session_start(['read_and_close' => true]);
require_once "../../includes/db.php";
header('Content-Type: application/json');

$comp_id = isset($_GET['comp_id']) ? (int)$_GET['comp_id'] : 0;
$uid  =$_SESSION['user_id'];

session_write_close();

$stmt = $pdo->prepare("
SELECT
    COUNT(*) OVER () AS count,
    a.id,
    a.acc_name,
    a.acc_categ
FROM accounts a
WHERE
    a.status = 'active'
    AND a.acc_categ IN ('cash_wallet', 'bank_wallet')

    AND EXISTS (
        SELECT 1
        FROM permissions p
        WHERE p.co_id = :comp_id
          AND p.user_id = :uid AND a.co_id= :comp_id1
          AND p.pm_acc_lvl IN (5,6,7)
          AND (
                p.pm_acc_id = a.id
                OR (
                    p.pm_acc_categ = a.acc_categ
                    AND (p.pm_acc_id IS NULL OR p.pm_acc_id = '')
                )
          )
    )
ORDER BY a.acc_name;
");
    
$stmt->execute([
    'uid' => $uid,
    'comp_id' => $comp_id,
    'comp_id1' => $comp_id
]);

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