<?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 abbreviateNumber($num) {
    $absNum = abs($num);

    if ($absNum >= 1000000000) {
        $formatted = round($absNum / 1000000000, 1) . 'B';
    } elseif ($absNum >= 1000000) {
        $formatted = round($absNum / 1000000, 1) . 'M';
    } elseif ($absNum >= 1000) {
        $formatted = round($absNum / 1000, 1) . 'K';
    } else {
        $formatted = $absNum;
    }

    return ($num < 0 ? '-' : '') . $formatted;
}

$stmt3 = $pdo->prepare("
    SELECT 
    d.co_id, d.t_cr,
    SUM(
        (CASE WHEN d.t_type = 'GR'  AND d.t_copy = 'O' THEN d.t_debit ELSE 0 END) +
        (CASE WHEN d.t_type = 'REC' AND d.t_copy = 'D' THEN d.t_debit ELSE 0 END) -
        (CASE WHEN d.t_type = 'DEL' AND d.t_copy = 'O' THEN d.t_credit ELSE 0 END) -
        (CASE WHEN d.t_type = 'OPBL' AND d.t_copy = 'O' THEN d.t_credit ELSE 0 END) +
        (CASE WHEN d.t_type = 'OPBL' AND d.t_copy = 'D' THEN d.t_debit ELSE 0 END)+
        (CASE WHEN d.t_type = 'CS INV' AND d.t_copy = 'D' THEN d.t_debit ELSE 0 END)-
        (CASE WHEN d.t_type = 'CS INV' AND d.t_copy = 'O' THEN d.t_credit ELSE 0 END)
    ) AS cr_bl2

FROM accounts a

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

WHERE 
 d.co_id = ?  
 AND
    -- ✅ Permission logic (safe version)
    EXISTS (
        SELECT 1
        FROM permissions p
        WHERE p.co_id = ?
          AND p.user_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 ('sales_person', 'customer')
    AND d.t_type IN ('DEL', 'GR', 'REC', 'OPBL', 'CS INV')

        AND d.t_date < DATE_SUB(NOW(), INTERVAL 9 HOUR)
    
");

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

if (!empty($data3)) {

    foreach ($data3 as $row) {

        $cr_bl2 = floatval($row['cr_bl2']);
        $value = abbreviateNumber($cr_bl2);

    // 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"]) . '">
                   ' . htmlspecialchars($value) . '
                </a>
              </span> ';
    }

} else {
    echo '0';
}
?>