<?php
session_start();
require_once 'dbconfig.php';
require_once 'db_connection.php';


$user_id = $_SESSION['user_id'];
                    $branch_id = $_SESSION['branch_id'];
                    $total_amount = 0;
                    $total_dis = 0;
                    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] != 0) {
                        $orderid = $_SESSION['order_id'];

                        $sql = "UPDATE mobiletemporarycart SET orderid='0' WHERE orderid='$orderid' AND hold=0 ";
                       if($conn->query($sql)){
                          //  $sql1 = "DELETE FROM mobileorders WHERE order_id ='$orderid'";
                       }


                        ///	$sql = "SELECT SUM(pro_qty) AS pro_qty , tempid,  pro_dis,pro_price,proid,proname,cover  FROM mobiletemporarycart LEFT JOIN mobileproducts ON mobileproducts.prid=mobiletemporarycart.proid
                        //WHERE mobiletemporarycart.user_id='$user_id' AND mobiletemporarycart.hold=0 AND mobiletemporarycart.orderid=0 GROUP BY  mobiletemporarycart.proid,mobiletemporarycart.pro_dis   ORDER BY mobiletemporarycart.tempid  DESC";
                        $sql = "SELECT
    SUM(mobiletemporarycart.pro_qty) AS pro_qty,
    mobiletemporarycart.tempid,
    mobiletemporarycart.pro_dis,
    mobiletemporarycart.pro_price,
    mobiletemporarycart.proid,
	mobiletemporarycart.pro_name,
    mobileproducts.proname,
	mobileproducts.price,
	mobileproducts.prid,
	mobiletemporarycart.pro_discount,
    mobileproducts.cover,
	mobiletemporarycart.pro_dis_price,
    mobiletemporarycart.discount_type
FROM
    mobiletemporarycart
LEFT JOIN
    mobileproducts ON mobileproducts.prid = mobiletemporarycart.proid
WHERE
   mobiletemporarycart.user_id='$user_id' AND mobiletemporarycart.branch_id='$branch_id' AND mobiletemporarycart.hold = 0 AND mobiletemporarycart.orderid = '0' OR mobiletemporarycart.orderid = '0'
GROUP BY
    mobiletemporarycart.tempid, mobiletemporarycart.pro_dis, mobiletemporarycart.pro_price, mobiletemporarycart.proid, mobileproducts.proname, mobileproducts.cover, mobileproducts.prid
ORDER BY
    mobiletemporarycart.tempid DESC"; 



                    } else {

                        $sql = "SELECT
    SUM(mobiletemporarycart.pro_qty) AS pro_qty,
    mobiletemporarycart.tempid,
    mobiletemporarycart.pro_dis,
    mobiletemporarycart.pro_price,
    mobiletemporarycart.proid,
	mobiletemporarycart.pro_name,
    mobileproducts.proname,
	mobileproducts.price,
	mobileproducts.prid,
	mobiletemporarycart.pro_discount,
    mobileproducts.cover,
	mobiletemporarycart.pro_dis_price,
    mobiletemporarycart.discount_type
FROM
    mobiletemporarycart
LEFT JOIN
    mobileproducts ON mobileproducts.prid = mobiletemporarycart.proid
WHERE
   mobiletemporarycart.user_id='$user_id' AND mobiletemporarycart.branch_id='$branch_id' AND mobiletemporarycart.hold = 0 AND mobiletemporarycart.orderid = 0
GROUP BY
    mobiletemporarycart.tempid, mobiletemporarycart.pro_dis, mobiletemporarycart.pro_price, mobiletemporarycart.proid, mobileproducts.proname, mobileproducts.cover, mobileproducts.prid
ORDER BY
    mobiletemporarycart.tempid DESC";
                    }

                    $result = $conn->query($sql);
                    $td = 0;
                    $total_row = 0;
                    $row = 0;
                    if ($result->num_rows > 0) {
                        $c = 1;
                        $qtyprice = 0;
                        $pro_discount = 0;
                        $pro_qty = 0;
                        $td = 0;
                        $total_dis = 0;
                        while ($row = $result->fetch_assoc()) {
                            $td = 0;
                            $pro_qty = 0;
                            $tempid = $row["tempid"];
                            $prid = $row["prid"];
                            $proid = $row["proid"];
                            $price = $row["price"];
                            $pro_name = $row["pro_name"];
                            $proname = $row["proname"];
                            $cover = $row["cover"];
                            $pro_dis = $row["pro_dis"];

                            $pro_dis_price = $row['pro_dis_price'];
                            $discount_type = $row["discount_type"];

                            $pro_discount = $row["pro_discount"];
                            $pro_price = $row["pro_price"];
                            $pro_qty = $row["pro_qty"];
                            $total_row = $total_row + 1;
                            //$discounted_price = ($pro_price / 100) * $pro_dis;
                            // $discounted_price = ($pro_price / 100) * $pro_discount;
                            //var_dump($pro_discount);

                            //$product_price = ($pro_price - $discounted_price) * $pro_qty;
                                $products = mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid ='$prid'");
                                $prinfo = mysqli_fetch_array($products);
                                $productprice = $prinfo['sellprice'];
                                
                            $qtyprice = $pro_price * $pro_qty;
                            if ($discount_type == 1) {


                                if ($productprice != $pro_price) {
                                    $pdis =  ($pro_price / 100) * $pro_discount;
                                    $pd = $pdis;
                                    // $p = ($qtyprice / 100) * $pro_discount;


                                    //$product_price = $qtyprice - $p;
                                    $product_price = $pro_price - $pd;

                                    // $product_price = $pro_price-$pdis;
                                } else {
                                    $pdis =  ($pro_price / 100) * $pro_discount;
                                    $pd = $pdis * $pro_qty;
                                    $p = ($qtyprice / 100) * $pro_discount;


                                    $product_price = $qtyprice - $p;
                                    // $product_price = $pro_price-$pdis;
                                }
                            } else {


                                $products = mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid ='$prid'");
                                $prinfo = mysqli_fetch_array($products);
                                $productprice = $prinfo['sellprice'];
                                if ($productprice != $pro_price) {
                                    //$pd = $pro_discount * $pro_qty;
                                    $pd = $pro_discount;
                                    $product_price = $pro_price - $pd;
                                } else {
                                    $pd = $pro_discount * $pro_qty;
                                    $product_price =  ($pro_price * $pro_qty) - $pd;
                                }

                                // $product_price = $pro_price-$pro_discount;
                            }

                            //if($price != $pro_price){


                            // $product_price = $product_price;
                            // if($row["pro_dis_price"]==0){
                            //$product_price = $product_price;
                            //}else{
                            //	$product_price = $row["pro_dis_price"];
                            //}
                            $total_amount = $total_amount + $product_price;
                            if ($discount_type == 1) {
                                if ($productprice != $pro_price) {
                                    $total_dis = $total_dis + $pdis;
                                    $td =  $total_dis;
                                } else {
                                    $total_dis = $total_dis + ($pdis * $pro_qty);
                                    $td =  $total_dis;
                                }
                            } else {
                                if ($productprice != $pro_price) {
                                    $total_dis = $total_dis + $pro_discount;
                                    $td =  $total_dis;
                                } else {
                                    $total_dis = $total_dis + ($pro_discount * $pro_qty);
                                    $td =  $total_dis;
                                }
                            }



                            //  $total_dis= $total_dis + ($pro_price-$row["pro_dis_price"]);
                            if ($pro_name == null) {
                                $pname = $proname;
                            } else {
                                $pname = $pro_name;
                            }


                            if ($pro_discount == 0) {
                                $dis = $pro_dis;
                            } else {
                                $dis = $pro_discount;
                            }

                            if ($discount_type == 1) {
                                $dtype = "%";
                            } else {
                                $dtype = "";
                            }

                            $stockinfo = mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid ='$prid'");
                            $stock = mysqli_fetch_array($stockinfo);

                           $sqty = $stock['qty'];



                           
                        }
                    }





// Retrieving POST data

$totalbillvalue = $total_amount + $td;
$cashamounthidden = (float)$_POST['cashamounthidden'];
$customer = $_POST['customer'];
$cashamount = (float)$_POST['cashamount'];
$cardno = $_POST['cardno'];
$cheque = $_POST['cheque'];
$cardpayment = (float)$_POST['cardpayment'];

//if($_POST['pay_type']=="cash_and_card"){
    $totalbalance = ($cashamount+$cardpayment) - $cashamounthidden;
    $cashamount = $cashamount + $cardpayment;
//}else{
  //  $totalbalance = $cashamount-$cashamounthidden;
//}

if(empty($_POST['tddiscount'])){
    $tddiscount = 0;
}else{
    $tddiscount = $_POST['tddiscount'];
}

$duedate = $_POST['duedate'];
$cheque_number = $_POST['cheque_number'];
$pay_type = $_POST['pay_type'];
$totalAmountvalue = $_POST['totalAmountvalue'];
$discount = $td;
$branch_id = $branch_id;
$country = $_POST['country'];
$city = $_POST['city'];
$deliveryCost = $_POST['deliveryCost'];
$branchid = "1";
$oid = "0";
$user_id = $_SESSION['user_id'];
$today = date('Y-m-d H:i:s');
$gift_number = $_POST['gift_number'];
$mobile_payment_method = $_POST['mobile_payment_method'];




// Calculate discount type
$last = substr($discount, -1);
$type = ($last == "%") ? 1 : 0;

// Fetch admin commission
if(!empty($admininfo)){
$admininfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileusers WHERE user_id='$user_id'"));
$adminrate = $admininfo['ucomission'];
}else{
    $adminrate = 0;
}
// Fetch customer commission
if(!empty($customerinfo)){
$customerinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
$customerrate = $customerinfo['comission'];
}else{
    $customerrate = 0;
}
// Apply discount if applicable

if ($discount > 0 && $discount < 101) {
   // $discounted_amount = (int)$totalbillvalue / 100 * (int)$discount;
    //$totalbillvalue = (int)$totalbillvalue - (int)$discounted_amount;
}

// Handling payment type and due amounts
//if ($pay_type == 'credit') {
   /* $due_amount = (float)$totalAmountvalue - (float)$cashamount;
    $paid_amount = (float)$cashamount;

    if ($due_amount >= 0) {
        $sql3 = "UPDATE mobilecustomers SET ccredit = ? WHERE coid = ?";
        $stmt = $conn->prepare($sql3);
        $stmt->bind_param("is", $due_amount, $customer);
        $stmt->execute();
        $stmt->close();
    } else {
        $sql3 = "UPDATE mobilecustomers SET ccredit = 0 WHERE coid = ?";
        $stmt = $conn->prepare($sql3);
        $stmt->bind_param("s", $customer);
        $stmt->execute();
        $stmt->close();
    }
        */
//} else {
    $due_amount = 0;
    $paid_amount = $totalbillvalue;
//}

// Check for valid payment input
//if ($totalbillvalue > 0) {
    
    if ($pay_type == 'Cash' && $cashamount == 0) {
        echo "7";
        exit;
    } elseif ($pay_type == 'Credit' && !$customer > 0) {
        echo "8";
        exit;
   
    } else {
        if ($pay_type == 'Credit') {
            $creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
            $credit_limit = $creditval['credit_limit'];
            if ($credit_limit < $totalAmountvalue) {
                echo "9";
               // echo "Customer credit limit is " . $credit_limit;
                exit;
            }
        }

        $comid = '';
        $orid = '';
        $stmt = $DB_con->prepare('SELECT IFNULL(MAX(order_id)+1,1) AS order_id FROM `mobileorders`');
        $stmt->execute();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            extract($row);
            $comid = $row['order_id'];
            $orid = "100$comid";
        }

        // Calculate commissions
        $admincommision = 0;
        $customercommision = 0;
        $cartorders = mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE orderid='0'");
        if ($cartorders->num_rows > 0) {
            while($row = $cartorders->fetch_assoc()) {
                if($row['pro_price'] > 1000){
                    
                    $admincommision += ($adminrate > 0) ? ((float)$row['pro_price'] / 100 * $adminrate) * $row['pro_qty'] : 0;
                    $customercommision += ($customerrate > 0) ? ((float)$row['pro_price'] / 100 * $customerrate) * $row['pro_qty'] : 0;
                }
            }
        }
       
        if ($oid != 0) {
            handleReturn($conn, $oid);
        } else {
            createOrder($conn,$cashamounthidden, $orid, $pay_type, $totalbillvalue,$tddiscount, $discount, $cashamount,$totalbalance, $due_amount, $cardno, $cheque, $duedate, $customer, $deliveryCost, $country, $city, $user_id, $today, $type, $branchid, $admincommision, $customercommision, $cheque_number, $gift_number, $mobile_payment_method, $cardpayment,$branch_id);
        }
    }
//}

function handleReturn($conn, $oid) {
    $return_qty = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
    $datetime = date("Y-m-d H:i:s");
    $amountdetails = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(return_amount) as returnamount,order_id,add_to_return FROM temp_return_qty WHERE order_id='$oid' AND add_to_return='1'"));
    $amount = $amountdetails['returnamount'];
    $sql5 = "INSERT INTO tbl_return (order_id, return_datetime, return_amount)VALUES ('$oid', '$datetime', '$amount')";
    if ($conn->query($sql5) === TRUE) {
        $last_id = $conn->insert_id;
        $returnitemlist = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$oid' AND return_type='1' AND add_to_return='1'");
        if ($returnitemlist->num_rows > 0) {
            while ($rw1 = $returnitemlist->fetch_assoc()) {
                $pid = $rw1['product_id'];
                $return_qty = $rw1['return_qty'];
                $orderr_id = $rw1['order_id'];
                $return_reson = $rw1['return_reson'];
                $sql6 = "INSERT INTO tbl_return_items (return_id, prid, qty,order_id,return_type,return_reson)VALUES ('$last_id', '$pid', '$return_qty', '$orderr_id','1','$return_reson')";
                if ($conn->query($sql6) === TRUE) {
                    $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));
                    $stock = $stockresult['qty'];
                    $stock += $return_qty;
                    $sql12 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";
                    $conn->query($sql12);
                    $sql7 = "DELETE FROM temp_return_qty";
                    $conn->query($sql7);
                    $sql8 = "UPDATE mobiletemporarycart SET orderid='$oid',return_to_new='1' WHERE orderid=0 AND hold=0 ";
                    $conn->query($sql8);
                }
            }
        }
    }
}

function createOrder($conn,$cashamounthidden, $orid, $pay_type, $totalbillvalue,$tddiscount, $discount, $cashamount,$totalbalance, $due_amount, $cardno, $cheque, $duedate, $customer, $deliveryCost, $country, $city, $user_id, $today, $type, $branchid, $admincommision, $customercommision, $cheque_number, $gift_number, $mobile_payment_method,$cardpayment,$branch_id) {
    
    $alldiscounts = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM all_discount_tbl WHERE all_discount_tbl_id='1' AND status='1'"));
    $tax = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tax WHERE tax_id='1' AND status='1'"));

    if(empty($alldiscounts)){
        $all_discount1 = 0;
        $discount_type = 0;
    }else{
        $all_discount1 = $alldiscounts['discount_val'];
        $discount_type = $alldiscounts['discount_type'];
    }
   
    if(empty($tax)){
        $tax1 = 0;
        $tax_type = 0;
    }else{
        $tax1 = $tax['tax'];
        $tax_type = $tax['tax_type'];
    }
   
    $oid1 = $_SESSION['order_id'];
    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] != 0 && mysqli_num_rows(mysqli_query($conn, "SELECT * FROM mobileorders WHERE order_id ='$oid1' AND (status ='2' OR status ='3')"))==1) {
        $orderid = $_SESSION['order_id'];
        $orderinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileorders WHERE order_id ='$orderid'"));

        $order_id = $orderinfo['order_id'];
        $orid = $orderinfo['orid'];
        $sql1 = "DELETE FROM mobileorders WHERE order_id ='$orderid'";
        if ($conn->query($sql1) === TRUE) {
           // $sql2 = "DELETE FROM beauticians_payments WHERE order_id ='$orderid'";
            //if ($conn->query($sql2) === TRUE) {
            //    $sql3 = "DELETE FROM invoice_other_details WHERE order_id ='$orderid'";
             //   $conn->query($sql3);
          //  }
        }
        $sql = "INSERT INTO mobileorders (order_id,orid,pay_option, amount, discount ,paid_amount,due_amount, payment_option_number,cheque_no,cheque_due_date, customer, delivery_cost, country, city,  user_id, create_at, dis_type,branch_id,status,admin_id,admin_commiision,customer_commision,cheque_number,gift_card_number,mobile_payment_method,all_discount,discount_type,tax,tax_type,cardpayment)
            VALUES ('$order_id','$orid','$pay_type', '$cashamounthidden', '$tddiscount' ,'$cashamount','$totalbalance', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branch_id','3','$user_id','$admincommision','$customercommision','$cheque_number','$gift_number','$mobile_payment_method','$all_discount1','$discount_type','$tax1','$tax_type','$cardpayment')";
    }else{
        $sql = "INSERT INTO mobileorders (orid,pay_option, amount, discount ,paid_amount,due_amount, payment_option_number,cheque_no,cheque_due_date, customer, delivery_cost, country, city,  user_id, create_at, dis_type,branch_id,status,admin_id,admin_commiision,customer_commision,cheque_number,gift_card_number,mobile_payment_method,all_discount,discount_type,tax,tax_type,cardpayment)
            VALUES ('$orid','$pay_type', '$cashamounthidden', '$tddiscount' ,'$cashamount','$totalbalance', '$cardno','$cheque','$duedate', '$customer', '$deliveryCost','$country','$city','$user_id', '$today' ,'$type' ,'$branch_id','3','$user_id','$admincommision','$customercommision','$cheque_number','$gift_number','$mobile_payment_method','$all_discount1','$discount_type','$tax1','$tax_type','$cardpayment')";
    }
   
   
   
   
   
   if ($conn->query($sql) === TRUE) {
        $last_id = $conn->insert_id;
        if ($last_id > 0) {
           // $beauticiancount = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE orderid='0' AND beautician !='1' GROUP BY beautician"));

         /*   $beauticiancountlist = mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE orderid='0' AND beautician !='1' GROUP BY beautician");
            if ($beauticiancountlist->num_rows > 0) {
                while($row1 = $beauticiancountlist->fetch_assoc()) {
                     $totalbeauticiancost = 0;
                   $beautician =  $row1['beautician'];
                    $cart = mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE orderid='0' AND beautician ='$beautician'");
                    if ($cart->num_rows > 0) {
                        while($row = $cart->fetch_assoc()) {
                            $pid = $row['proid'];
                            $pro_qty = $row['pro_qty'];
                            $beautician_cost = $row['beautician_cost1'];

                            $pinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid ='$pid'"));
                            $product_material_status = $pinfo['product_material_status'];
                            if($product_material_status==1){
                                $totalbeauticiancost = $totalbeauticiancost + ($beautician_cost * $pro_qty);
                            }
                        }
                        $sql5 = "INSERT INTO `beauticians_payments`(`beautician_id`, `payment`, `order_id`) VALUES ('$beautician','$totalbeauticiancost', '$last_id')";
                        $conn->query($sql5);
                    }

                }
            }
            */

            $sql = "UPDATE mobiletemporarycart SET orderid='$last_id' WHERE orderid=0 AND user_id='$user_id' AND hold=0 ";
            $conn->query($sql);
            $sql = "INSERT INTO `invoice_other_details`(`invoice_other_id`, `order_id`, `branch_id`) VALUES (null,'$last_id', '1')";
            $conn->query($sql);
           // if($beautician!=1){
               
           // }       
            
            //$sql4 = "UPDATE all_discount_tbl  SET discount_val='0', discount_type='0' WHERE all_discount_tbl_id =1";
           // $conn->query($sql4);
          // updateStock($conn, $last_id, $pay_type, $cashamounthidden, $customer);
           echo $last_id;
        }
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

function updateStock($conn, $last_id, $pay_type, $totalAmountvalue, $customer) {
    $sql2 = "SELECT * FROM mobiletemporarycart WHERE orderid='$last_id' ORDER BY tempid DESC";
    $result2 = $conn->query($sql2);
    if ($result2->num_rows > 0) {
        while ($row = $result2->fetch_assoc()) {
            $proid = $row["proid"];
            $pro_qty = $row["pro_qty"];
            $sql3 = "UPDATE tbl_stock SET qty= qty-$pro_qty WHERE prid='$proid'";
            $conn->query($sql3);
            if ($pay_type == 'Credit') {
                $creditval = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customer'"));
                $credit_limit = $creditval['credit_limit'];
                if ($credit_limit > $totalAmountvalue) {
                    $sql4 = "UPDATE mobilecustomers SET ccredit= '$totalAmountvalue' WHERE coid='$customer'";
                    $conn->query($sql4);
                }
            }
        }
    }
}

?>
