INSERT INTO `tbl_acc_details`(`_date`, `description`, `cheque_no`, `payee`, `amount`, `type`, `tag_id`, `account_id`, `transaction_id`, `event`, `is_send`, `account_code`, `location_id`, `cheque_date`, `sent_on`, `log_id`, `created_on`,transaction_code)
select 
case when pa.payment_type = 'CHEQUE' then date(psd.received_date) else psd.cash_date end as _date
,'by api - ' as description
,case when pa.payment_type = 'CHEQUE' then psd.cheque_no else '' end as cheque_no
,c.customer_name as payee
,sum(pa.allocation_amount) as amount
,'CR' as `type`
,0 as tag_id
,(case 
	when pa.payment_type = 'CHEQUE' then  
    ( case when c.category = '1' then '28' else '151' end )
else '30' end ) as account_id
,pa.return_cheque_id as transaction_id
,'return_cheque' as `event`
,0 as is_send
,(case  when pa.payment_type = 'CHEQUE' then 
 ( case when c.category = '1' then 'Cheque in hand SLTB' else 'Cheque In Hand- Dealersale' end )
else 'Cash in hand' end) as account_code
,bil.fn_companyCode as location_id
,case when pa.payment_type = 'CHEQUE' then date(psd.cheque_date) else psd.cash_date end as cheque_date
,now() as sent_on
,'' as log_id
,now() as created_on
,cr.code as transaction_code

from tbl_payment_allocation_return_cheque pa
inner join tbl_return_cheques cr on cr.id = pa.return_cheque_id
inner join tbl_sale_invoice si on si.id = pa.invoice_id
inner join tbl_branch_inventory_locations bil on bil.id = si.location_id
inner join tbl_customers c on c.customer_id = si.customer_id
inner join tbl_payment_summary_details psd on psd.id = pa.payment_id
inner join tbl_payment_summary ps on ps.id = pa.ps_id
left join tbl_bank_accounts ba on ba.id = psd.bank_account_id
where pa.return_cheque_id = ?
group by pa.payment_id