<?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 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,
    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)
    ) AS cr_bl2

FROM accounts a

JOIN transactions d 
    ON a.id = d.t_cr

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

    AND (
        d.t_date >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') 
        AND d.t_date < DATE_SUB(NOW(), INTERVAL 9 HOUR)
    )
");

$stmt3->execute([$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);

    $statusClass = ($cr_bl2 < 0) ? "text-danger" : "text-light";

        echo '<span class="price ' . $statusClass . '">
                <a class="item fetch-cr_unclbl_yearly"
                   data-toggle="modal"
                   data-target="#Modalrep2"
                   data-loc_id="' . htmlspecialchars($row["t_tt_doc"]) . '"
                   data-usr="' . htmlspecialchars($row["t_cr"]) . '">
                   ' . htmlspecialchars($value) . '
                </a>
              </span> ';
    }

} else {
    echo '0';
}
?>