<?php
session_start();
require_once "../../includes/db.php";

header('Content-Type: text/html; charset=UTF-8');

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

// Function to abbreviate numbers
function formatUGX($amount) {
    return number_format((float)$amount, 0, '.', ',');
}


$stmt3 = $pdo->prepare("
SELECT 
    d.co_id, d.t_cr,
     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 cash

FROM accounts a

JOIN transactions d 
    ON a.id = d.t_cr

WHERE 
    -- ✅ Permission logic (safe version)
    EXISTS (
        SELECT 1
        FROM permissions p
        WHERE p.co_id = ?
          AND p.user_id = ?   AND d.co_id = ?
        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')
    AND d.t_type IN ('BNK', 'EXP', 'REC' , 'CTFR', 'csh_adj');
    
");

$stmt3->execute([$comp_id,$user_id,$comp_id]);
$data3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);

if (!empty($data3)) {

    foreach ($data3 as $row) {

        $cr_bl2 = floatval($row['cash']);

        // Simple and clear condition
        $statusClass = ($cr_bl2 < 0) ? "text-danger" : "text-light";

        echo '<span class="price ' . $statusClass . '">
                <a class="item fetch-unclearedbl"
                   data-toggle="modal"
                   data-target="#ModalBasic_1"
                   data-loc_id="' . htmlspecialchars($row["co_id"]) . '"
                   data-usr="' . htmlspecialchars($row["t_cr"]) . '">
                    ' . formatUGX($cr_bl2) . '
                </a>
              </span> ';
    }



} else {
    echo '0';
}
?>