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

$coid   = $_SESSION['co_id'];

session_write_close();

$inv_limit  = $_GET['inv_limit'] ?? 10;
$inv_offset = $_GET['inv_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, d.t_status,
            SUM(CASE WHEN d.t_type = 'DEL' THEN d.t_credit ELSE 0 END) AS total_debit_DEL,
            SUM(CASE WHEN d.t_type = 'GR' THEN d.t_debit ELSE 0 END) AS total_credit_GR,
             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 total_result
        FROM transactions d
        JOIN accounts u ON d.t_cr = u.id        
        WHERE 
            d.t_tt_doc = :storeid
            AND u.acc_categ = 'sales_person'
            AND d.t_type IN ('DEL', 'GR')
       GROUP BY d.t_doc_no, d.t_type
        ORDER BY d.t_id ASC
        LIMIT :inv_limit OFFSET :inv_offset
");

$stmt->bindValue(':storeid', $storeid, PDO::PARAM_INT);
$stmt->bindValue(':inv_limit', (int)$inv_limit, PDO::PARAM_INT);
$stmt->bindValue(':inv_offset', (int)$inv_offset, PDO::PARAM_INT);
$stmt->execute();

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