<?php
$dRange=$_POST['dRange'];
$reportInfo=['Date :'.$dRange];
$general->getFromToFromString($dRange,$from,$to);
$supplier_id=intval($_POST['supplier_id']);
$type=intval($_POST['type']);


$q[]='date between '.$from.' and '.$to;
if($supplier_id>0){
    $q[]='supplier_id='.$supplier_id;
}
if($type>0){
    $q[]='type='.$type;
}
$purchases=$db->selectAll('purchase','where '.implode(' and ',$q));

$rData=[];
$tSubTotal=0;
$tDiscount=0;
$tNetTotal=0;
$serial=1;
if(!empty($purchases)){
    $supIDs=[];
    foreach($purchases as $pur){
        $supIDs[$pur['supplier_id']]=$pur['supplier_id'];
    }
    $suppliers=$db->selectAll('suppliers','where id in('.implode(',',$supIDs).')');
    $general->arrayIndexChange($suppliers,'id');
    foreach($purchases as $pur){
        $tSubTotal+=$pur['sub_total'];
        $tDiscount+=$pur['discount'];
        $tNetTotal+=$pur['total'];
        $rData[]=[
            's' => $serial++,
            'su'=> $suppliers[$pur['supplier_id']]['name'],
            'i' => $pur['supplier_invoice_no'],
            'd' => $general->make_date($pur['date']),
            'st'=> $general->numberFormat($pur['sub_total']),
            'di'=> $general->numberFormat($pur['discount']),
            'n' => $general->numberFormat($pur['total']),
            'p'=>'<button onclick="purchase_details_view('.$pur['id'].')" class="btn btn-success">Details</button>'
        ];
    }


}
$rData[]=[
    's'=>'',
    'su'=>['t'=>'Total','b'=>1],
    'i'=>['t'=>''],
    'd'=>['t'=>''],
    'st'=>['t'=>$general->numberFormat($tSubTotal),'b'=>1],
    'di'=>['t'=>$general->numberFormat($tDiscount),'b'=>1],
    'n'=>['t'=>$general->numberFormat($tNetTotal),'b'=>1],
    //'a'=>['t'=>''],
];


$fileName='purRep_'.TIME.rand(0,999).'.txt';
$report_data=array(
    'name'      => 'purRep'.date('d_m_Y',$from).'_'.date('d_m_Y',$to),
    'title'     => 'Purchase Report',
    'info'      => $reportInfo,
    'fileName'  => $fileName,
    'head'=>array(
        array('title'=>"#"          ,'key'=>'s' ,'w'=>5),
        array('title'=>"Supplier"   ,'key'=>'su','w'=>10),
        array('title'=>"Sup Inv No" ,'key'=>'i','w'=>10),
        array('title'=>"Date"       ,'key'=>'d' ,'hw'=>15),
        array('title'=>"Subtotal"   ,'key'=>'st','al'=>'r'),
        array('title'=>"Discount"   ,'key'=>'di','al'=>'r'),
        array('title'=>"Net Payable",'key'=>'n','al'=>'r'),
        array('title'=>"Details"       ,'key'=>'p'),
    ),
    'data'=>$rData
);
$jArray[__LINE__]=$report_data;
$gAr['report_data']= $report_data;
textFileWrite(json_encode($report_data),ROOT_DIR.'/print_file/'.$fileName);
$jArray['html']     = $general->fileToVariable(ROOT_DIR.'/ajax/report.phtml');
$jArray['status']=1;   
?>
