<?php
require_once "../../includes/db.php";
header('Content-Type: application/json');
session_start();

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

session_write_close();

$ovSR_limit  = $_GET['ovSR_limit'] ?? 10;
$ovSR_offset = $_GET['ovSR_offset'] ?? 0;
//$storeid = $_GET['storeid'] ?? 0;

$stmt = $pdo->prepare("
SELECT
            d.t_date, DATE_FORMAT(d.t_date, '%d %b %y') AS M_date,d.co_id, a.acc_name, d.t_tt_doc, d.t_ct_det, 
            SUM(CASE WHEN d.t_type = 'DEL' THEN d.t_credit ELSE 0 END) AS total_credit_DEL,
            SUM(CASE WHEN d.t_type = 'GR' THEN d.t_debit ELSE 0 END) AS total_debit_GR,
            SUM(CASE WHEN d.t_type = 'REC' THEN d.t_debit ELSE 0 END) AS total_debit_CSH,
            (SUM(CASE WHEN d.t_type = 'DEL' THEN d.t_credit ELSE 0 END) 
             - SUM(CASE WHEN d.t_type = 'GR' THEN d.t_debit ELSE 0 END)) AS daily_sales,
            (SUM(CASE WHEN d.t_type = 'GR' THEN d.t_debit ELSE 0 END) 
             + SUM(CASE WHEN d.t_type = 'REC' THEN d.t_debit ELSE 0 END)) 
             - (SUM(CASE WHEN d.t_type = 'DEL' THEN d.t_credit ELSE 0 END)) AS result_short
        FROM transactions d
        JOIN accounts a ON d.t_cr = a.id 
        JOIN users x ON x.id = a.user_id

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,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 = 'sales_person'
            AND d.t_type IN ('DEL', 'GR', 'REC')
        GROUP BY d.t_date, a.user_id

ORDER BY d.t_date DESC
        LIMIT :ovSR_limit OFFSET :ovSR_offset
");

//$stmt->bindValue(':storeid', $storeid, PDO::PARAM_INT);
$stmt->bindValue(':comp_id', $comp_id, PDO::PARAM_INT);
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->bindValue(':comp_id1', $comp_id, PDO::PARAM_INT);
$stmt->bindValue(':ovSR_limit', (int)$ovSR_limit, PDO::PARAM_INT);
$stmt->bindValue(':ovSR_offset', (int)$ovSR_offset, PDO::PARAM_INT);
//$stmt->bindValue(':user_id1', $user_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
exit;