<?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();

$ovRCL_limit  = $_GET['ovRCL_limit'] ?? 10;
$ovRCL_offset = $_GET['ovRCL_offset'] ?? 0;
//$storeid = $_GET['storeid'] ?? 0;

$stmt = $pdo->prepare("
            SELECT
                a.co_id,
                a.id,
                a.acc_name,
                SUM(d.t_credit) AS total_credit
            FROM transactions d
            INNER JOIN accounts a
                ON d.t_cr = a.id AND d.co_id = a.co_id
            INNER JOIN account_start_date_track x
                ON x.acc_id = a.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 (1,2,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 = 'Pending'
  AND d.t_copy = 'O'
  AND a.acc_categ IN ('cash_wallet','bank_wallet','stock')
   AND d.t_type IN ('CTFR','STFR','BNK')
  AND d.t_date >= x.from_date
GROUP BY a.co_id, a.id, a.acc_name

ORDER BY a.acc_name ASC
        LIMIT :ovRCL_limit OFFSET :ovRCL_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(':ovRCL_limit', (int)$ovRCL_limit, PDO::PARAM_INT);
$stmt->bindValue(':ovRCL_offset', (int)$ovRCL_offset, PDO::PARAM_INT);
//$stmt->bindValue(':user_id1', $user_id, PDO::PARAM_INT);
$stmt->execute();

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