<?php
session_start();
require '../../includes/db.php';

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

/* ===============================
   ðŸ“ˆ 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 d.co_id = :comp_id
          AND p.user_id = :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='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]);
$daily = $stmt1->fetchAll(PDO::FETCH_ASSOC);


/* ===============================
   ðŸ¥§ Pending vs Collected
================================ */
$sql2 = "
   SELECT 
        SUM(CASE WHEN t_status = 'Pending' THEN t_debit ELSE 0 END) AS pending,
        SUM(CASE WHEN t_status = 'Confirmed' THEN t_debit ELSE 0 END) AS collected
    FROM transactions
    WHERE co_id = :comp_id
    AND t_type = 'REC' AND t_copy = 'D'
    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,
    "pending" => $status['pending'] ?? 0,
    "collected" => $status['collected'] ?? 0
]);