<?php
session_start(['read_and_close' => true]);
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;

session_write_close();

// 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 a.acc_type = 'Cash' AND a.acc_categ='expense' AND a.acc_source='Internal'  AND d.t_copy = 'O' THEN d.t_credit ELSE 0 END) 
      
    ) AS expense_today

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 = ?
          AND p.user_id = ?   AND d.co_id = ?
        AND p.pm_acc_lvl IN (0,2,3,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 (  'expense')
    AND DATE(d.t_date) = DATE(DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 3 HOUR));
    
");

$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['expense_today']);

    if($cr_bl2<0){
        $statusClass = ($cr_bl2 < 0) ? "text-danger" : "";
    }
     else{    $statusClass = ($cr_bl2 > 0) ? "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';
}
?>