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

$exp_limit  = $_GET['exp_limit'] ?? 10;
$exp_offset = $_GET['exp_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) 
        
    ) AS top_expenses

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_id
        AND p.pm_acc_lvl IN (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','Pending')
    AND a.acc_categ IN ( 'expense')
    AND d.t_date >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')
    GROUP BY a.acc_name ORDER BY top_expenses DESC
        LIMIT :exp_limit OFFSET :exp_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(':exp_limit', (int)$exp_limit, PDO::PARAM_INT);
$stmt->bindValue(':exp_offset', (int)$exp_offset, PDO::PARAM_INT);
$stmt->execute();

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