<?php
session_start(['read_and_close' => true]);
require '../../includes/db.php';

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

session_write_close();

/* ===============================
   ðŸ“ˆ Daily Revenue
================================ */
$sql1 = "
    SELECT DATE(d.t_date) as date, SUM(d.t_debit) as amount
     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 = :comp_id
          AND p.user_id = :user_id  AND d.co_id =  :comp_id1   
        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='Confirmed'
     AND d.t_type = 'REC' AND d.t_copy = 'D'
    AND MONTH(d.t_date) = MONTH(CURRENT_DATE)
    AND YEAR(d.t_date) = YEAR(CURRENT_DATE)
    GROUP BY DATE(d.t_date)
    ORDER BY DATE(d.t_date);
";

$stmt1 = $pdo->prepare($sql1);
$stmt1->execute(['comp_id' => $comp_id, 'user_id' => $user_id, 'comp_id1' => $comp_id]);
$daily = $stmt1->fetchAll(PDO::FETCH_ASSOC);


/* ===============================
   ðŸ¥§ Pending vs Collected
================================ */
$sql2 = "
SELECT 
        SUM(CASE WHEN t_type = 'DEL' THEN t_debit ELSE 0 END) -
        SUM(CASE WHEN t_type = 'GR' THEN t_credit ELSE 0 END) AS sales,
        SUM(CASE WHEN t_type = 'REC' THEN t_debit ELSE 0 END) AS collected
    FROM transactions
    WHERE co_id = :comp_id
    AND t_type IN ('REC','DEL', 'GR') AND t_copy = 'D'
    AND t_status = 'Confirmed'
    AND MONTH(t_date) = MONTH(CURRENT_DATE)
    AND YEAR(t_date) = YEAR(CURRENT_DATE);
";

$stmt2 = $pdo->prepare($sql2);
$stmt2->execute(['comp_id' => $comp_id]);
$status = $stmt2->fetch(PDO::FETCH_ASSOC);


/* ===============================
   ðŸš€ Output JSON
================================ */
echo json_encode([
    "daily" => $daily,
    "sales" => $status['sales'] ?? 0,
    "collected" => $status['collected'] ?? 0
]);