<?php
ini_set('session.cookie_secure', 1);
session_start(['read_and_close' => true]);
require_once "../../includes/db.php";
header('Content-Type: text/html; charset=UTF-8');

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

session_write_close();

try {
   $store_id = isset($_GET['store_id']) ? intval($_GET['store_id']) : 0;

    $stmt3 = $pdo->prepare("
        SELECT 
            d.t_tt_doc,
            d.t_cr,
            u.acc_name,
            d.t_date,
            'MONTHLY' AS t_type,
            u.id,
            (
                SUM(CASE WHEN d.t_type = 'GR' AND t_copy = 'O' THEN d.t_debit ELSE 0 END) +
                SUM(CASE WHEN d.t_type = 'REC' AND t_copy = 'D' THEN d.t_debit ELSE 0 END) -
                SUM(CASE WHEN d.t_type = 'DEL' AND t_copy = 'O' THEN d.t_credit ELSE 0 END) -
                SUM(CASE WHEN d.t_type = 'OPBL' AND t_copy = 'O' THEN d.t_credit ELSE 0 END) +
                SUM(CASE WHEN d.t_type = 'OPBL' AND t_copy = 'D' THEN d.t_debit ELSE 0 END)
            ) AS cr_bl2
        FROM transactions d
        JOIN accounts u ON d.t_cr = u.id AND d.co_id = u.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,1,3,5,6,7)
          AND (
                p.pm_acc_id = u.id 
                OR (
                    p.pm_acc_categ = u.acc_categ 
                    AND (p.pm_acc_id IS NULL OR p.pm_acc_id = '')
                )
          )
    )

    -- ✅ Filters
    
        
            AND d.t_status IN ('Confirmed','Approved') 
            AND u.acc_categ = 'sales_person'
            AND d.t_type IN ('DEL', 'GR', 'REC', 'OPBL')
            AND d.t_date < DATE_SUB(NOW(), INTERVAL 9 HOUR)
        GROUP BY u.acc_name ORDER BY cr_bl2 ASC;
    ");

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

    if (!empty($data3)) {
        foreach ($data3 as $row) {
            $t_type = $row['t_type'] ?? ''; // Ensure $t_type is defined
            
    // Default styles
            $lineStyle = "color: #6c757d;"; // Default gray
            $dateStyle = "color: #FFFFFF;";
            $statusStyle = "color: #6c757d;";

            // Assign styles based on transaction type
            switch ($t_type) {
                case 'DEL':
                   $lineStyle = "font-size: 14px; color: #008080; border-top: 0.5px solid #6c757d;";
                    $dateStyle = "font-size: 14px; color: #008080; border-top: 0.5px solid #6c757d;";
                    $statusStyle ="font-size: 14px; color: #008080; border-top: 0.5px solid #6c757d;";
                    break;
                case 'GR':
                    $lineStyle = "font-size: 14px; color: #d50592 ; border-top: 0.5px solid #6c757d;";
                    $dateStyle = "font-size: 14px; color:  #d50592 ; border-top: 0.5px solid #6c757d;";
                    $statusStyle = "font-size: 14px; color:  #d50592 ; border-top: 0.5px solid #6c757d;";
                    break;
                case 'REC':
                    $lineStyle = "font-size: 14px; color: #43bf10 ; border-top: 0.5px solid #6c757d;";
                    $dateStyle = "font-size: 14px; color:  #43bf10 ; border-top: 0.5px solid #6c757d;";
                    $statusStyle = "font-size: 14px; color:  #43bf10 ; border-top: 0.5px solid #6c757d;";
                    break;
                    case 'STFR':
                    $lineStyle = "font-size: 14px; color: #E9967A;";
                    $dateStyle = "font-size: 14px; color: #E9967A;";
                    $statusStyle = "font-size: 14px; color: #E9967A;";
                    break;
                
                case 'PRCH':
                    $lineStyle = "font-size: 14px; color: #00d821 ;";
                    $dateStyle = "font-size: 14px; color: #00d821 ;";
                    $statusStyle = "font-size: 14px; color: #00d821 ;";
                    break;
                case 'RET PRCH':
                    $lineStyle = "font-size: 14px; color: #6c757d;";
                    $dateStyle = "font-size: 14px; color: #6c757d;";
                    $statusStyle = "font-size: 14px; color: #6c757d;";
                    break;
                    case 'DATE':
                    $lineStyle = "font-weight: bold; font-size: 16px; color: #FFFFFF;";
                    $dateStyle = "font-weight: bold; font-size: 16px; color: #000;";
                    $statusStyle = ($row['t_amount'] < 0) ? "font-weight: bold; font-size: 16px; color: #FFFFFF;" : "font-weight: bold; font-size: 16px; color: #FFFFFF;";
                    break;
                case 'SHT/EXC':
                    $lineStyle = "font-weight: bold; font-size: 16px; color: #000; border-top: 0.5px solid #6c757d;";
                    $dateStyle = "font-weight: bold; font-size: 16px; color: #000; border-top: 0.5px solid #6c757d;";
                    $statusStyle = ($row['t_amount'] < 0) ? "font-weight: bold; font-size: 16px; color: #dc3545; border-top: 0.5px solid #6c757d;" : "font-weight: bold; font-size: 16px; color: #000; border-top: 0.5px solid #6c757d;";
                    break;
                case 'MONTHLY':
                    $lineStyle = "font-size: 16px; color: transparent; border-bottom: 0.5px solid #f2f3f4 ;";
                    $dateStyle = "font-size: 16px; color: #000; border-bottom: 0.5px solid #f2f3f4;";
                    $statusStyle = ($row['cr_bl2'] < 0) ? " font-size: 16px; color: #dc3545; border-bottom: 0.5px solid #f2f3f4;" : " font-size: 16px; color: #000; border-bottom: 0.5px solid #f2f3f4;";
                    break;
                case '-YEARLY TOTAL':
                    $lineStyle = "font-weight: bold; font-size: 16px; color: #000; border-bottom: 1px solid #6c757d;";
                    $dateStyle = "font-weight: bold; font-size: 16px; color: #FFFFFF; border-top: 1px solid #6c757d;";
                    $statusStyle = ($row['t_amount'] < 0) ? "font-weight: bold; font-size: 16px; color: #dc3545; border-bottom: 1px solid #6c757d;" : "font-weight: bold; font-size: 16px; color: #000; border-bottom: 1px solid #6c757d;";
                    break;
                case 'GRAND TOTAL':
                    $lineStyle = "font-weight: bold; font-size: 20px; color: #FFFFFF;";
                    $dateStyle = "font-weight: bold; font-size: 20px; color: #000;";
                    $statusStyle = ($row['t_amount'] < 0) ? "font-weight: bold; font-size: 20px; color: #dc3545;" : "font-weight: bold; font-size: 20px; color: #000;";
                    break;
            }

            echo '<tr class="data-row" style="border: none;">
                <td style="' . $dateStyle . '">
                    <a data-toggle="modal" class="item fetch-cr_unclbl_yearly" data-target="#ModalBasic_2"
                       data-loc_id="' . htmlspecialchars($row["t_tt_doc"]) . '"
                       data-usr="' . htmlspecialchars($row["t_cr"]) . '"
                       data-accname="' . htmlspecialchars($row["acc_name"]) . '">
                      ' . htmlspecialchars($row["acc_name"] ?? '') . '
                    </a>
                </td>
                
                  <td style="' . $lineStyle . '">
                    <a class="item" 
                       data-loc_id="' . htmlspecialchars($row["t_tt_doc"]) . '"
                       data-usr="' . htmlspecialchars($row["t_cr"]) . '"
                       data-accname="' . htmlspecialchars($row["acc_name"]) . '">
                      ' . htmlspecialchars($row["t_type"] ?? '') . '
                    </a>
                </td>
                
                 <td style="text-align: right; ' . $statusStyle . '">
                    <a data-toggle="modal" class="item fetch-cr_unclbl_yearly" data-target="#ModalBasic_2" 
                       data-loc_id="' . htmlspecialchars($row["t_tt_doc"]) . '"
                       data-usr="' . htmlspecialchars($row["t_cr"]) . '"
                       data-accname="' . htmlspecialchars($row["acc_name"]) . '">
                      ' . number_format($row["cr_bl2"], 0, '.', ',') . '
                    </a>
                </td>
            </tr>';

            if ($t_type === 'SHT/EXC' || $t_type === 'GRAND TOTAL') {
                echo '<tr class="grouped" style="border-bottom: 2px solid #000;">
                        <td colspan="4"></td>
                    </tr>';
            }
        }
    } else {
        echo '<tr><td colspan="4" class="text-center text-warning">No matching records found.</td></tr>';
    }
} catch (PDOException $e) {
    echo '<tr><td colspan="4" class="text-center text-danger">Error fetching data.</td></tr>';
    error_log("Database Error: " . $e->getMessage());
}
?>
