<?php
    $general->createLog('sale',$_POST);
    $not_check_credit_limit = 0;
    if($db->permission(103)){
        $not_check_credit_limit = intval($_POST['not_check_credit_limit']);
    }
    $draftID    = intval($_POST['draftID']);
    $pay_type    = intval($_POST['pay_type']);
    $cID        = intval($_POST['cID']);
    $due_day        = intval($_POST['due_day']);
    $base_id        = intval($_POST['base_id']);
    $products   = $_POST['products'];
    $note   = $_POST['note']??'';
    $saleDate   = strtotime($_POST['saleDate']);
    $discount   = floatval($_POST['discount']);
    $c          = $smt->customerInfoByID($cID);
    $base          = $db->baseInfoByID($base_id);
    $truk_rent_pay_by       = intval($_POST['truk_rent_pay_by'])==1?1:2;
    $truk_list       = $_POST['truk_list']??[];
    $ade_list       = $_POST['ade_list']??[];
    $all_truk = $smt->get_all_truk();
    $all_additional_expense = $smt->get_all_additional_expense();

    if($cID<=0){$error=fl();setMessage(1,'Select a customer');}
    elseif($base_id<=0){$error=fl();setMessage(1,'Select a Base');}
    elseif(empty($base)){$error=fl();setMessage(63,'Base');}
    elseif($due_day<0){$error=fl();setMessage(63,'Due day');}
    elseif(empty($c)){$error=fl(); setMessage(63,'customer');}
    elseif($c['base_id']!=$base_id){$error=fl();setMessage(63,'Base');}
    elseif($saleDate<strtotime('-2 years')){$error=fl();setMessage(63,'Purchase date');}
    elseif($pay_type!=PAY_TYPE_CASH&&$pay_type!=PAY_TYPE_CREDIT){$error=fl();setMessage(63,'pay type');}
    elseif(empty($products)){$error=fl();setMessage(63,'Products');}
    elseif(empty($truk_list)){$error=fl();setMessage(63,'Truk List');}
    else{
        if($saleDate==TODAY_TIME){
            $saleDate=TIME;
        }
        $jArray[fl()]=$truk_list;
        $jArray[fl()]=$ade_list;
        $product = $db->selectAll('products','where id in('.implode(',',array_keys($products)).')','id,title,sale_price,unit_id,stock,data,VAT,unit_cost');
        $general->arrayIndexChange($product);
        $sProduct = [];
        $sub_total=0;
        $total_vat=0;
        $total_cost=0;
        $total_amount=0;
        $product_total_discount=0;
        foreach($products as  $pID=>$ps){
            $p = @$product[$pID];  
            $jArray[fl()][$pID]=$p;

            $data = $general->getJsonFromString($p['data']);
            if(!isset($products[$pID])) {$error=fl(); setMessage(1,'Products'); break;}
            elseif(array_key_exists($pID,$sProduct)){$error=fl();setMessage(69,$p['title']); break;}
            elseif($ps['qty']<=0){$error=fl();setMessage(63,'Quantity for '.$p['title']); break;}
            elseif($p['stock']<=0){$error=fl();setMessage(1,$p['title'].' stock out!'); break;}
            elseif($p['stock']<$ps['qty']){$error=fl();setMessage(1,$p['title'].' stock out!'); break;}
            else{ 
                $qty = $ps['qty'];
                $total_cost += $qty*$p['unit_cost'];
                $product_total = $qty*$ps['sale_price'];
                if($product_total<0){$error=fl();setMessage(63,'sale price for '.$p['title']); break;}
                $sub_total+=$product_total;
                $sProduct[$pID]=[
                    'product_id'=> $pID,
                    'sale_qty'  => $qty,
                    'free_qty'  => 0,
                    'total_qty' => 0,
                    'unit_price'=> $ps['sale_price'],
                    'sub_total' => $product_total,
                    'total'     => $product_total,
                    'unit_cost' => $p['unit_cost']
                ];
            }
        }
        foreach($truk_list as $tl){
            $truk_id=$tl['truk_id'];
            if(!isset($all_truk[$truk_id])){$error=fl();setMessage(1,'Some of invalid truk');}
            elseif($tl['truk_rent']<0){$error=fl();setMessage(63,'Rent for '.$all_truk[$truk_id]['title']);}
        }
        if(!isset($error)){
            $total = $sub_total-$discount;
            if($sub_total<$discount){$error = fl(); setMessage(63,'discount');}
            elseif($total<0){$error = fl(); setMessage(63,'discount');}
            
            
            if(!isset($error)){ 
                $customer_due_data = $acc->customer_due_details($cID);
                $customer_balance=-$customer_due_data['customer_balance'];
                $customer_due_invoice=[];
                if(!empty($customer_due_data['due_data'])){
                    foreach($customer_due_data['due_data'] as $d){
                        $due_pay_type=$d['pay_type']==PAY_TYPE_CASH?'Cash':'Credit';
                        $aging=$general->get_time_difference($saleDate,$d['date'],'d');
                        $customer_due_invoice[]=[
                            'date'      => $d['date'],
                            'pay_type'  => $due_pay_type,
                            'aging'     => $aging,
                            'due'       => $d['due'],
                            'invoice_no'=> $d['invoice_no'],
                        ];
                    }
                }

            }
            if(!isset($error)){ 
                
                $db->transactionStart();
                $sale_data=[
                    'customer_closing_balance'=>$customer_balance,
                    'customer_due_invoice'=>$customer_due_invoice
                ];

                $data = [
                    'customer_id'   => $cID,
                    'pay_type'      => $pay_type,
                    'date'          => $saleDate,
                    'sub_total'     => $sub_total,
                    'discount'      => 0,
                    'extra_discount'=> $discount,
                    'VAT'           => 0,
                    'total'         => $total,
                    'data'          => json_encode($sale_data),
                    'cost'          => $total_cost,
                    'note'          => $note,
                    'collection_date'=>strtotime('+'.$due_day.' day',$saleDate),
                    'base_id'        => $base_id,
                ];
                $jArray[fl()]=$data;
                $jArray[fl()]=$sProduct;
                $db->arrayUserInfoAdd($data);
                $sID = $db->insert('sale',$data,true);
                if(!$sID){$error=fl(); setMessage(66);}
                else{
                    $prefix = $base['code'].'-';
                    $invoice_no = $db->setAutoCode('sale_invoice_no',$sID,$prefix);
                    if($invoice_no==false){$error=fl();setMessage(66);}
                    foreach($sProduct as $pID=>$data){
                        $data['sale_id']=$sID;
                        $sdID=$db->insert('sale_products',$data,true);
                        if($sdID){
                            $p = $smt->productInfoByID($pID,false);
                            $log=$smt->productStockChangeLog($pID,$data['total_qty'],ST_CH_SALE,$sdID,$saleDate);  
                            if($log==false){$error=fl();setMessage(66);}
                            $nextQty=$p['stock'];
                            $nextQty-=$data['total_qty'];
                            $update=$smt->update_product_closing_stock($pID,$jArray);
                            if($update==false){$error=fl();setMessage(66);}
                            // $where=['id'=>$pID];
                            // $update=$db->update('products',['stock'=>$nextQty],$where);
                            // if($update==false){$error=fl();setMessage(66);break;}
                        }
                    }
                    foreach($truk_list as $tl){
                        $truk_id=$tl['truk_id'];
                        $data=[
                            'sale_id'   => $sID,
                            'truk_id'       => $truk_id,
                            'rent'          => $tl['truk_rent'],
                            'time'          => $saleDate,
                            'pay_by'        => $truk_rent_pay_by,
                        ];
                        $insert=$db->insert('sale_truk',$data,true);
                        if($insert==false){$error=fl();setMessage(66);}
                    }
                    if(!empty($ade_list)){
                        foreach($ade_list as $ade){
                            $ade_id=$ade['ade_id'];
                            $data=[
                                'sale_id'   => $sID,
                                'additional_expense_id'        => $ade_id,
                                'truk_id'       => $ade['truk_id'],
                                'pay_by'        => $ade['pay_by'],
                                'amount'        => $ade['amount'],
                                'time'          => $saleDate,
                            ];
                            $insert=$db->insert('sale_additional_cost',$data,true);
                            if($insert==false){$error=fl();setMessage(66);}
                        }
                    }
                    if(!isset($error)){
                        $saleHead=$acc->getSystemHead(AH_DEALER_SALE);
                        if($saleHead==false){$error=fl();setMessage(66);}
                        $cashHead=$acc->getSystemHead(AH_CASH);
                        if($cashHead==false){$error=fl();setMessage(66);}
                        $customer_head=$acc->getCustomerHead($c);
                        if($customer_head==false){$error=fl();setMessage(66);}
                        
                    }
                    if(!isset($error)){
                        $sale_amount=$total;
                        $particular='Sale '.$c['name'].' '.$invoice_no;
                        $voucher=$acc->voucher_create(V_T_SALE_CASH_CUSTOMER,$sale_amount,$customer_head,$saleHead,$saleDate,$particular,$sID);
                        if($voucher==false){$error=fl();setMessage(66);}
                        
                    }
                }
                if($draftID>0){
                    $data=['isActive'=>2];
                    $where = ['id'=>$draftID ];
                    $update = $db->update('sale_draft',$data,$where);
                    if(!$update){$error=fl(); setMessage(66);}
                }
                $ac = false; 
                if(!isset($error)){
                    if(!empty($c['mobile'])){
                        $sms_text="Dear Valued Customer, Your Invoice with Tk $total ready for delivery. You will get soon. Thanks Panacea Agrovet Ltd 01313444291";
                        $sms_data=[
                            'text'=>$sms_text,
                        ];
                        $data=[
                            'data'=>json_encode($sms_data),
                            'mobile'=>$c['mobile'],
                            'add_time'=>TIME
                        ];
                        $sms_send=$db->insert('queue_sms',$data,true);
                        if(!$sms_send){setMessage(66);$error=fl();}
                    }
                }
                if(!isset($error)){
                    $jArray['status'] = 1;
                    $jArray['sale_id'] = $sID;
                    $ac = true;
                    setMessage(2,'Products sale successfully');
                }
                $db->transactionStop($ac);
            }
        }   
}
$general->createLog('sale',$jArray);