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

$coid   = $_SESSION['co_id'];
$user_id   = $_SESSION['user_id'];
$comp_id = $_GET['comp_id'] ?? 0;

session_write_close();

$acc_limit  = $_GET['acc_limit'] ?? 10;
$acc_offset = $_GET['acc_offset'] ?? 0;
$storeid = $_GET['storeid'] ?? 0;

$stmt = $pdo->prepare("
    SELECT 
    d.co_id, d.t_cr, a.acc_name,a.acc_type,
    SUM(
        (CASE WHEN  d.t_copy = 'O' THEN d.t_credit ELSE 0 END) -
       
        (CASE WHEN  d.t_copy = 'D' THEN d.t_debit ELSE 0 END)
        
    ) AS balance

FROM accounts a

JOIN transactions d 
    ON a.id = d.t_cr AND d.co_id = a.co_id

WHERE 
    -- ✅ Permission logic (safe version)
    EXISTS (
        SELECT 1
        FROM permissions p
        WHERE p.co_id = :comp_id
          AND p.user_id = :user_id   AND d.co_id = :comp_id1
        AND p.pm_acc_lvl IN (0,2,4,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 = '')
                )
          )
    )

    -- ✅ Filters
    
    AND d.t_status IN ('Confirmed','Approved')
    AND a.acc_categ IN ( 'cash_wallet', 'bank_wallet')
    AND d.t_type IN ('BNK', 'EXP', 'REC' , 'CTFR', 'csh_adj')
    AND a.acc_source IN ('Internal')
    GROUP BY a.acc_name ORDER BY a.acc_type DESC
        LIMIT :acc_limit OFFSET :acc_offset
");

//$stmt->bindValue(':storeid', $storeid, PDO::PARAM_INT);
$stmt->bindValue(':comp_id', $comp_id, PDO::PARAM_INT);
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->bindValue(':comp_id1', $comp_id, PDO::PARAM_INT);
$stmt->bindValue(':acc_limit', (int)$acc_limit, PDO::PARAM_INT);
$stmt->bindValue(':acc_offset', (int)$acc_offset, PDO::PARAM_INT);
$stmt->execute();

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