<?php
    $dRange = $_POST['dRange'];
    $general->getFromToFromString($dRange,$from,$to);
    $q=["date between $from and $to",'isActive=1',"base_id=".$userData['base_id']];
    $draft = $db->selectAll('sale_draft','where '.implode(' and ',$q));
    $tSubTotal=0;
    $tDiscount=0;
    $tTotal=0;
    $s=1;
    $q=[];
    $q[]='isActive in(1,0)';

    $q[]  ='base_id='.  $userData['base_id'];

    $sq='where '.implode(' and ',$q);

    $customers=$db->selectAll('customer',$sq.' order by name asc','id,name,code,due_day,base_id');


    $general->arrayIndexChange($customers,'id');
    if(!empty($customers)){
        foreach($customers as $k=>$p){
            $customers[$k]['name']=$p['code'].' '.$p['name'];
        }
    }

    if(!empty($draft)){

        foreach($draft as $d){
            $sData =  $general->getJsonFromString($d['data']);
            $sub_total=0;
            $discount=0;
            foreach($sData['products'] as $p){
                $sub_total+=$p['salePrice_tp']*$p['qty'];
                $discount+=$p['discount'];
            }
            $discount+=$sData['discount'];
            $total = $sub_total-$discount;
            $tSubTotal+=$sub_total;
            $tDiscount+=$discount;
            $tTotal+=$total;
            $rData[]=[
                's'=>$s++,
                'c'=>$customers[$d['customer_id']]['name']??'',
                'd'=>$general->make_date($d['date']),
                'su'=>$general->numberFormat($tSubTotal),
                'di'=>$general->numberFormat($discount),
                't'=>$general->numberFormat($total),
            ];
        }
    }
    $rData[]=[
        's'=>['t'=>''],
        'c'=>['t'=>'Total','b'=>1],
        'd'=>['t'=>'',],
        'su'=>['t'=>$general->numberFormat($tSubTotal),'b'=>1],
        'di'=>['t'=>$general->numberFormat($tDiscount),'b'=>1],
        't'=>['t'=>$general->numberFormat($tTotal),'b'=>1],
    ];

    $fileName='productsSaleDraftList'.TIME.rand(0,999).'.txt';
    $report_data=array(
        'name'      => 'productsSaleDraftList',
        'title'     => 'Products Sale Draft List',
        'head'=>array(
            array('title'=>"#"         ,'key'=>'s','hw'=>5),
            array('title'=>"Customer"  ,'key'=>'c'),
            array('title'=>"Date"      ,'key'=>'d'),
            array('title'=>"Subtotal"  ,'key'=>'su','al'=>'r'),
            array('title'=>"Discount"  ,'key'=>'di','al'=>'r'),
            array('title'=>"Net amount",'key'=>'t','al'=>'r'),

        ),
        '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;