<?php
$general->createLog('pending_order_create',$_POST);
    $userData = $db->userInfoByID(USER_ID);
    if($userData['type']==USER_TYPE_MPO){
        $base_id        = $userData['base_id'];
    }
    else{
        $base_id        = intval($_POST['base_id']);   
    }
    $cID        = intval($_POST['cID']);
    $pay_type   = intval($_POST['pay_type']);
    $due_day    = intval($_POST['due_day']);
    $note       = $_POST['note']??'';
    $products   = $_POST['products'];
    $saleDate   = strtotime($_POST['saleDate']);
    $discount   = floatval($_POST['discount']);
    $c          = $smt->customerInfoByID($cID);
    $base        = $db->baseInfoByID($base_id);
    if($cID<=0){$error=fl();setMessage(1,'Select a customer');}
    elseif(empty($c)){$error=fl(); setMessage(63,'customer');}
    elseif($base_id<=0){$error=fl();setMessage(1,'Select a Base');}
    elseif(empty($base)){$error=fl();setMessage(63,'Base');}
    elseif($c['base_id']!=$base_id){$error=fl();setMessage(63,'Base');}
    elseif($due_day<0){$error=fl();setMessage(63,'Due day');}
    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');}
    else{
        $product = $db->selectAll('products','where id in('.implode(',',array_keys($products)).')','id,title,sale_price,unit_id,stock,data');
        $general->arrayIndexChange($product,'id');
        $sProduct = [];
        $subTotal=0;
        foreach($products as  $pID=>$ps){
            $p = @$product[$pID];  
            $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['total_qty']<=0){$error=fl();setMessage(63,'Quantity for '.$p['title']); break;}
            elseif($ps['qty']<=0){$error=fl();setMessage(63,'Quantity for '.$p['title']); break;}
            elseif($ps['free_qty']<0){$error=fl();setMessage(63,'free Quantity for '.$p['title']); break;}
            elseif($p['stock']<=0){$error=fl();setMessage(1,$p['title'].' stock out!'); break;}
            elseif($p['stock']<$ps['total_qty']){$error=fl();setMessage(1,$p['title'].' stock out!'); break;}
            elseif($p['sale_price']<$ps['salePrice']){$error=fl();setMessage(1,$p['title'].' invalid sale price!'); break;}
            //elseif($p['sale_price']<$ps['discount']){$error=fl();setMessage(1,$p['title'].' invalid discount!'); break;}
            else{ 
                $product_discount = ($p['sale_price']-$ps['salePrice'])*$ps['qty'];
                $sale_qty = $ps['qty'];
                $free_qty = $ps['free_qty'];
                $total_qty = $ps['qty'];

                $total_qty+=$free_qty;

                $sdTotal = $sale_qty*$p['sale_price'];
                $total = $sdTotal-$ps['discount'];
                if($total_qty!=$ps['total_qty']){$error=fl();setMessage(63,'Quantity for '.$p['title']); break;}
                elseif($free_qty!=$ps['free_qty']){$error=fl();setMessage(63,'Quantity for '.$p['title']); break;}
                elseif($ps['discount']!=$product_discount){$error=fl();setMessage(63,'Discount for '.$p['title']); break;}
                elseif($total<0){$error=fl();setMessage(63,'Total for '.$p['title']); break;}

                $subTotal+=$total;

            }
        }
        if(!isset($error)){
            $customer_due_data = $acc->customer_due_details($cID);
            $cData = $general->getJsonFromString($c['data']);
            if($customer_due_data['customer_balance']!=0){//নতুন কাস্টমারের ক্ষেত্রে এই লিমিট লাগবে না।
                $balance =$customer_due_data['customer_balance']+floatval(@$cData['credit_limit'])-$total;
                $jArray[fl()]=$customer_due_data;
                $jArray[fl()]=$balance;
                if($balance<0){$error=fl();setMessage(1,'Credit limit over');}
                else if($customer_due_data['due_date']>0&&$customer_due_data['due_date']<TIME){$error=fl();setMessage(1,"You don't have enough balance");}
            }
            
        }
        if(!isset($error)){
            if($subTotal<=$discount){$error = fl(); setMessage(1,'discount');}
            else{
                $sData=['products'=>$products,'discount'=>$discount,'note'=>$note,'pay_type'=>$pay_type] ;

                $data=[
                    'customer_id'=>$cID,
                    'due_day'=>$due_day,
                    'base_id'=>$base_id,
                    'date'=>$saleDate,
                    'data'=>json_encode($sData),
                    'isActive'=>1,
                ];

                $insert = $db->insert('sale_draft',$data);
                if($insert){$jArray['status']=1; setMessage(2,'Order added');}
                else{$error=fl(); setMessage(66);}

            }

        }
    }
    $general->createLog('pending_order_create',$jArray);