<?php
require_once "../../includes/db.php";
header('Content-Type: application/json');
session_start(['read_and_close' => true]);

$coid   = $_SESSION['co_id'];
$user_id   = $_SESSION['user_id'];

session_write_close();

$csh_limit  = $_GET['csh_limit'] ?? 10;
$csh_offset = $_GET['csh_offset'] ?? 0;
$storeid = $_GET['storeid'] ?? 0;

$stmt = $pdo->prepare("
    SELECT
            d.co_id,d.t_date,  DATE_FORMAT(d.t_date, '%d %b%y') AS M_date, d.t_tt_doc, d.t_doc_no,d.t_type, d.t_ct_det,u.acc_name,a.acc_name, d.t_status,
            SUM(CASE WHEN d.t_type = 'rec' THEN d.t_credit ELSE 0 END) AS total_debit_DEL,
            SUM(CASE WHEN d.t_type = 'exp' THEN d.t_debit ELSE 0 END) AS total_credit_GR,
             SUM(CASE WHEN d.t_type = 'rec' THEN d.t_credit ELSE 0 END)+
            SUM(CASE WHEN d.t_type = 'exp' THEN d.t_debit ELSE 0 END) AS total_result
        FROM transactions d
        JOIN accounts u ON d.t_cr = u.id   AND d.co_id = u.co_id
        JOIN accounts a ON d.t_ct_det = a.id  
        JOIN permissions p ON (u.id = p.pm_acc_id OR (u.acc_categ=p.pm_acc_categ AND p.pm_acc_id='' )) AND 
        p.co_id = u.co_id AND p.co_id = :coid AND p.user_id = :user_id AND p.pm_acc_lvl IN (0,2,4,5,6,7)
        WHERE d.t_tt_doc = u.id AND
             d.t_status = 'Confirmed'
            AND u.acc_categ IN ('cash_wallet', 'bank_wallet')
           AND d.t_type IN ('rec', 'exp')
           AND DATE(d.t_date) = DATE(DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 5 HOUR))
       GROUP BY d.t_doc_no, d.t_type
        ORDER BY d.t_id ASC
        LIMIT :csh_limit OFFSET :csh_offset
");

//$stmt->bindValue(':storeid', $storeid, PDO::PARAM_INT);
$stmt->bindValue(':coid', $coid, PDO::PARAM_INT);
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->bindValue(':csh_limit', (int)$csh_limit, PDO::PARAM_INT);
$stmt->bindValue(':csh_offset', (int)$csh_offset, PDO::PARAM_INT);
$stmt->execute();

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