<?php
require_once '../../includes/db.php';

$comp_id = $_GET['comp_id'];
$accountno = $_GET['accountno'];

$sql = "
SELECT 
   d.t_id, d.co_id,d.t_date, d.t_ct_det, b.acc_name AS accname_exp, c.acc_name AS acc_rec,  d.t_cr, a.acc_name,a.acc_type, d.t_type, d.t_conf_by, d.t_credit, d.t_debit,    SUM(
        COALESCE(d.t_credit, 0) - COALESCE(d.t_debit, 0)
    ) OVER (
        PARTITION BY a.id 
        ORDER BY d.t_date, d.t_id
    ) AS running_balance


   

FROM accounts a

JOIN transactions d 
    ON a.id = d.t_cr AND d.co_id = a.co_id
   LEFT JOIN accounts b 
    ON b.id = d.t_ct_det  
    LEFT JOIN accounts c 
    ON c.user_id = d.t_conf_by  

WHERE 
    d.t_cr=:accountno AND d.co_id=:comp_id
    AND d.t_status IN ('Confirmed','Approved','Pending')
    GROUP BY d.t_id ORDER BY d.t_date DESC, d.t_id DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':accountno' => $accountno,
    ':comp_id' => $comp_id
]);

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