<?php require_once('../auth/auth.php');require_once('../auth/acid_balance.php');?>
<?php 
if(isset($_POST['sal_invoice'])){
   $invoice    = $_POST['sal_invoice'];
   $tdate      = $_POST['tdate'].' '.$time;
   $tdddate      = $_POST['tdate'];   
   $c_acid     = $_POST['c_acid'];
   $f_acid     = $_POST['f_acid'];
   $d_acid     = $_POST['d_acid'];
   $discount   = ($_POST['sldiscount']>0)?$_POST['sldiscount']:0;
   $delivary_c = ($_POST['delivary_c']>0)?$_POST['delivary_c']:0;
   $m_acid     = $_POST['m_acid'];
   $payment    = $_POST['slpayment'];
   $details    = $_POST['details'];
   $wh_id      = $_POST['wh_id'];
   $d_man      = $_POST['d_man'];
   $m_invoice  = $_POST['m_invoice'];
   $net_amount = $_POST['sl_totalc'];
   $us_em_id   = $_POST['us_em_id'];
   $sltype     = $_POST['sltype'];
   $Bank_check = $_POST['Bank_check'];
   
   if ($sltype=='ERSL'){ 
       $rec_type = 'R_R';
   } else if($sltype=='ECSL'){
       $rec_type = 'W_R';
   } else if($sltype=='INSL'){ 
       $rec_type = 'R_I';
   }
    
   
  if (isset($_POST['c_gsm'])) {
     $c_gsm     = $_POST['c_gsm'];
     $c_name    = $_POST['c_name'];
     $c_address = $_POST['c_address'];
     $payment   = (($net_amount + $delivary_c)-$discount);

     $chcus=mysqli_query($conn,"SELECT c_id FROM c_customer WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND c_gsm='$c_gsm' LIMIT 1");

     if (mysqli_num_rows($chcus)<1) {
        mysqli_query($conn,"INSERT INTO `c_customer`(`coid`, `bid`, `brid`, `c_name`, `c_gsm`, `c_address`) VALUES ('$coid','$bid','$brid','$c_name','$c_gsm','$c_address')") or die(mysqli_error($conn));
     }

     $c_cus=mysqli_fetch_assoc(mysqli_query($conn,"SELECT c_id FROM c_customer WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND c_gsm='$c_gsm' LIMIT 1"))['c_id'];
  }
  
//   $c_id = @$c_cus?$c_cus:$uid;


  $c_id   = @$c_cus?$c_cus:$uid;
  $cus_id = @$c_cus?$c_cus:$c_acid;
  
  
  
    $chinvoice=mysqli_query($conn,"SELECT invoice FROM transaction WHERE coid='$coid' AND invoice='$invoice' LIMIT 1");
    if (mysqli_num_rows($chinvoice)>0 || $net_amount < 0.01) {}else {

    mysqli_query($conn,"INSERT INTO `order_list`(`coid`, `bid`, `brid`, `acid`, `invoice`, `order_type`, `wh_id`, `pro_id`, `item_code`, `pro_type`, `plus`, `qty`, `pro_unit`, `unit_val`, `out_qty`, `run_qty`, `pu_price`, `avg_price`, `sale_price`, `discount`, `dis_amount`, `amount`, `net_amount`, `t_amount`, `tax`, `profit`, `details`, `d_man`, `userid`, `datetime`, `active`) SELECT `coid`, `bid`, `brid`, '$cus_id', `invoice`, `order_type`, '$wh_id', `pro_id`, `item_code`, `pro_type`, `plus`, (qty*unit_val), `pro_unit`, `unit_val`, `out_qty`, `run_qty`, `pu_price`, `avg_price`, `sale_price`, `discount`, `dis_amount`, `amount`, `net_amount`, `t_amount`, `tax`, `profit`, `details`, '$d_man','$uid', '$tdate', 1 FROM `order_list_edit` WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice' ORDER BY eoid ASC ") or die(mysqli_error($conn));
   

    mysqli_query($conn,"INSERT INTO `imei_tracker`(`coid`, `bid`, `brid`, `acid`, `invoice`, `order_type`, `wh_id`, `pro_id`, `imei_code`, `imei_color`, `mfg_date`, `exp_date`, `plus`, `pu_price`, `sale_price`, `date`, `active`) SELECT `coid`, `bid`, `brid`, '$cus_id', `invoice`, `order_type`, '$wh_id', `pro_id`, `imei_code`, `imei_color`,`mfg_date`,`exp_date`, `plus`, `pu_price`, `sale_price`, `date`, 1 FROM `imei_tracker_edit` WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));

      $c_gcatid= mysqli_fetch_assoc(mysqli_query($conn,"SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$c_acid' LIMIT 1"))['gcatid'];

      $sl_row= mysqli_fetch_assoc(mysqli_query($conn,"SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='sale' LIMIT 1"));
      $sl_acid   = $sl_row['acid'];
      $sl_gcatid = $sl_row['gcatid'];

      $inv_row= mysqli_fetch_assoc(mysqli_query($conn,"SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='stock' LIMIT 1"));
      $inv_acid   = $inv_row['acid'];
      $inv_gcatid = $inv_row['gcatid'];

      $cogs_row= mysqli_fetch_assoc(mysqli_query($conn,"SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='cogs' LIMIT 1"));
      $cogs_acid   = $cogs_row['acid'];
      $cogs_gcatid = $cogs_row['gcatid'];

      $avg_total= mysqli_fetch_assoc(mysqli_query($conn,"SELECT SUM(avg_price*qty) avg_cost FROM order_list WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'"))['avg_cost'];

      mysqli_query($conn,"INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$c_acid', '$sl_acid', '$c_id', '$c_gcatid', '$sl_gcatid', '$invoice','$m_invoice', LEFT('$invoice ',4),'$details','esale','$net_amount','$tdate','$time','$uid','$us_em_id','1'),
          ('$coid','$bid','$brid','$cogs_acid', '$inv_acid', '$uid', '$cogs_gcatid', '$inv_gcatid', '$invoice','$m_invoice', 'COGS','$details','esale','$avg_total','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));
      $lastid = mysqli_insert_id($conn);
      mysqli_query($conn,"DELETE FROM order_list_edit WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));

      mysqli_query($conn,"DELETE FROM imei_tracker_edit WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));

        if ($f_acid>0 && $delivary_c>0) {

          $f_gcatid= mysqli_fetch_assoc(mysqli_query($conn,"SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$f_acid' LIMIT 1"))['gcatid'];

           mysqli_query($conn,"INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$c_acid', '$f_acid', '$uid', '$c_gcatid', '$f_gcatid', '$invoice','$m_invoice', 'R','Delevery Charge','esale_delivary','$delivary_c','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));

        $tmp_f = balance($f_acid)['ac_balance'];
        $f_acid_balance = (@$tmp_f)?$tmp_f:0;
        mysqli_query($conn,"UPDATE accounts SET balance='$f_acid_balance' WHERE coid='$coid' AND acid ='$f_acid'") or die(mysqli_error($conn));
        }

        if ($d_acid>0 && $discount>0) {

          $d_gcatid= mysqli_fetch_assoc(mysqli_query($conn,"SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$d_acid' LIMIT 1"))['gcatid'];

           mysqli_query($conn,"INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$d_acid', '$c_acid', '$uid', '$d_gcatid', '$c_gcatid', '$invoice','$m_invoice', 'P','Sales Discount','esale_discount','$discount','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));

        $tmp_d = balance($d_acid)['ac_balance'];
        $d_acid_balance = (@$tmp_d)?$tmp_d:0;
        mysqli_query($conn,"UPDATE accounts SET balance='$d_acid_balance' WHERE coid='$coid' AND acid ='$d_acid'") or die(mysqli_error($conn));
        }

 if ($m_acid !=='NaN' && $payment>0  ) {
          $m_gcatid= mysqli_fetch_assoc(mysqli_query($conn,"SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$m_acid' LIMIT 1"))['gcatid'];

           mysqli_query($conn,"INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$m_acid', '$c_acid', '$uid', '$m_gcatid', '$c_gcatid', '$invoice', '$m_invoice', '$rec_type','Sales Receive','esale_payment','$payment','$tdate','$time','$uid','$us_em_id','1')") or die(mysqli_error($conn));

        $tmp_m = balance($m_acid)['ac_balance'];
        $m_acid_balance = (@$tmp_m)?$tmp_m:0;
        mysqli_query($conn,"UPDATE accounts SET balance='$m_acid_balance' WHERE coid='$coid' AND acid ='$m_acid'") or die(mysqli_error($conn));

        }else{

          mysqli_query($conn,"INSERT INTO tran_cheque(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$m_acid', '$c_acid', '$uid', '$m_gcatid', '$c_gcatid', '$invoice', '$m_invoice', '$rec_type','Sales Receive Cheque Payment','$Bank_check','$payment','$tdate','$time','$uid','$us_em_id','0')") or die(mysqli_error($conn));
        }         

        $tmp_inv  = balance($inv_acid)['ac_balance'];
        $tmp_c    = balance($c_acid)['ac_balance'];
        $tmp_sl   = balance($sl_acid)['ac_balance'];
        $tmp_cogs = balance($cogs_acid)['ac_balance'];

        $inv_acid_balance  = (@$tmp_inv)?$tmp_inv:0;
        $c_acid_balance    = (@$tmp_c)?$tmp_c:0;
        $sl_acid_balance   = (@$tmp_sl)?$tmp_sl:0;
        $cogs_acid_balance = (@$tmp_cogs)?$tmp_cogs:0;

        mysqli_query($conn,"UPDATE accounts SET balance='$inv_acid_balance' WHERE coid='$coid' AND acid ='$inv_acid'") or die(mysqli_error($conn));
        mysqli_query($conn,"UPDATE accounts SET balance='$c_acid_balance' WHERE coid='$coid' AND acid ='$c_acid'") or die(mysqli_error($conn)); 
        mysqli_query($conn,"UPDATE accounts SET balance='$sl_acid_balance' WHERE coid='$coid' AND acid ='$sl_acid'") or die(mysqli_error($conn));
        mysqli_query($conn,"UPDATE accounts SET balance='$cogs_acid_balance' WHERE coid='$coid' AND acid ='$cogs_acid'") or die(mysqli_error($conn));     


        $year = date('Y');
        $invoice_parts = explode('-', $invoice);
        $prefix = $invoice_parts[0];
        mysqli_query($conn,"UPDATE voucher_no SET v_no=(v_no + 1) WHERE coid='$coid' AND v_type ='$prefix' AND v_year='$year'") or die(mysqli_error($conn));

        /////////////////////////////////// Installment Part Start ///////////////////////////////////

      if (isset($_POST['ins_qty'])) {
          $ins_type          = $_POST['ins_type'];
          $ins_qty           = $_POST['ins_qty'];
          $first_ins_date    = $_POST['first_ins_date'];
          $reference_name    = $_POST['reference_name'];
          $reference_number  = $_POST['reference_number'];
          $reference_address = $_POST['reference_address'];

          $ins_total  = ((($net_amount + $delivary_c)-$discount)-$payment);

          $perins_set = floor($ins_total/$ins_qty);

          $lastins    = $ins_total - ($perins_set * $ins_qty);
            

          if ($ins_type =='Daily') {
            $incr = 'day';
          } else if($ins_type =='Weekly'){
                $incr = 'week';
          } else if($ins_type =='Monthly'){
            $incr = 'month';
          }
              
          for ($i=1; $i <= $ins_qty -1; $i++) { 
            $in = $i-1;
            $finsdate = date('Y-m-d', strtotime(+$in.$incr, strtotime($first_ins_date)));

            mysqli_query($conn,"INSERT INTO `intallment`(`coid`, `bid`, `brid`,`acid`,`ins_active_date`, `invoice`,`in_type`, `ins_qty`,`ins_qty_total`, `per_ins`,`due_ins`, `ins_type`, `ins_date`, `status`, `service_name`, `reference_name`, `reference_number`, `reference_address`)  VALUES ('$coid','$bid','$brid','$c_acid','$tdate','$invoice',LEFT('$invoice ',4), '$i','$ins_qty', '$perins_set','$perins_set', '$ins_type',(IF((1 < $i),'$finsdate','$first_ins_date')), 'unpaid','$details','$reference_name','$reference_number','$reference_address')") or die(mysqli_error($conn));
          }

          $date_set=date('Y-m-d', strtotime('+1'.$incr, strtotime($finsdate)));
          $lastinsbalance= $lastins+$perins_set;

          mysqli_query($conn,"INSERT INTO `intallment`(`coid`, `bid`, `brid`,`acid`,`ins_active_date`, `invoice`,`in_type`, `ins_qty`,`ins_qty_total`, `per_ins`,`due_ins`, `ins_type`, `ins_date`, `status`, `service_name`, `reference_name`, `reference_number`, `reference_address`)  VALUES ('$coid','$bid','$brid','$c_acid','$tdate', '$invoice',LEFT('$invoice ',4), '$i+1','$ins_qty', '$lastinsbalance','$lastinsbalance', '$ins_type', '$date_set', 'unpaid','$details','$reference_name','$reference_number','$reference_address')") or die(mysqli_error($conn));

      }

/////////////////////////////////// Installment Part End ///////////////////////////////////
      
        if (isset($_POST['email'])) {
          // Email Part Here
        }
        
        ///////

        if (isset($_POST['sms'])){
            $smssend=   $_POST['sms'];
            $chbll = invbalance($c_acid,$tdddate,$lastid);
            $pr_due = ($chbll)?$chbll['pr_due']:0;
            if ($smssend =='yes') {
                
                if (isset($_POST['c_gsm'])) {
                     $PhoneNumber =$_POST['c_gsm'];
                     $smstext= mysqli_fetch_assoc(mysqli_query($conn,"SELECT smstext FROM sms_tamp_all WHERE  status=1 AND type='ECSL' AND coid='$coid' AND bid='$bid' AND brid='$brid' LIMIT 1 "))['smstext'];  
                     $content_val   = [$net_amount,$delivary_c,$discount,$payment];
                     $content_var   = ["%invoice%","%d_charge% ","%discount%","%payment%"]; 
                     $newmsg = str_replace($content_var, $content_val, $smstext);
                     $msgmsg = urlencode($newmsg);
                     // echo "Cash  seals sms";
                } else if($sltype=='ERSL') {
                     $prebalance= $pr_due;
                     $PhoneNumber = mysqli_fetch_array(mysqli_query($conn,"SELECT ac_number FROM accounts WHERE  acid='$c_acid' LIMIT 1 "))['ac_number'];
                     $smstext= mysqli_fetch_assoc(mysqli_query($conn,"SELECT smstext FROM sms_tamp_all WHERE  status=1 AND type='ERSL' AND coid='$coid' AND bid='$bid' AND brid='$brid' LIMIT 1 "))['smstext'];  
   
                     $content_val   = [$net_amount,$delivary_c,$discount,$prebalance,$payment,$c_acid_balance];
                     $content_var   = ["%invoice%","%d_charge% ","%discount%","%prebalance%","%payment%","%lastbalance%"]; 
                     $newmsg = str_replace($content_var, $content_val, $smstext);
                     $msgmsg = urlencode($newmsg);
                     
                    // echo "Retail seals sms";
                } else if($sltype=='INSL') {
                     $prebalance= $pr_due;
                     $PhoneNumber = mysqli_fetch_array(mysqli_query($conn,"SELECT ac_number FROM accounts WHERE  acid='$c_acid' LIMIT 1 "))['ac_number'];
                     $smstext= mysqli_fetch_assoc(mysqli_query($conn,"SELECT smstext FROM sms_tamp_all WHERE  status=1 AND type='INSL' AND coid='$coid' AND bid='$bid' AND brid='$brid' LIMIT 1 "))['smstext'];  
   
                     $content_val   = [$net_amount,$delivary_c,$discount,$prebalance,$payment,$c_acid_balance];
                     $content_var   = ["%invoice%","%d_charge% ","%discount%","%prebalance%","%payment%","%lastbalance%"]; 
                     $newmsg = str_replace($content_var, $content_val, $smstext);
                     $msgmsg = urlencode($newmsg);
                     
                    // echo "INS seals sms";
                }
                     if ($msgmsg && strlen($PhoneNumber) >= 11 && strlen($PhoneNumber) <= 14){require_once('../sms/api_key_access.php');}
            }
        }
        /////


  }
}
?>
