<?php
ob_start();
if(!isset($_SESSION)){ session_start(); } 
include 'load.php'; 
if(!isset($_SESSION['quotation'])) { $_SESSION['quotation'] = array(); } 
if(isset($_POST['product']) and isset($_POST['quntity'])){
    

    $cart_item = array();
    $productid = $_POST['product'];
    $qty = $_POST['quntity'];
    $description = $_POST['description'];
    $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
    $stockinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$productid'"));

    if($stockinfo['qty'] > $qty){
        if(count($_SESSION['quotation']) != 0){  
            $c=0;
            foreach ($_SESSION['quotation'] as $key => $cart_item) {	
                if($cart_item['product_id'] == $productid){
                    $c=0;
                    if($stockinfo['qty'] > $cart_item['quantity'] + $qty){
                        $_SESSION['quotation'][$key]['quantity'] = $cart_item['quantity'] + $qty;
                        echo '<script> window.location.href = "add-quotation.php"; </script>';
                        
                        exit;
                    }else{
                        echo '<script> window.location.href = "add-quotation.php"; </script>';
                       
                        exit;
                    }
                    
                }else{
                    $c=1;
                    
                }
            }
            if($c==1){
                array_push($cart_item,
                        $cart_item['product_id'] = $productid,
                        $cart_item['quantity'] = $qty,   
                        $cart_item['description'] = $description 
                    );
                    array_push($_SESSION['quotation'], $cart_item);
                   echo '<script> window.location.href = "add-quotation.php"; </script>';
            }



        }else{
            array_push($cart_item,
                $cart_item['product_id'] = $productid,
                $cart_item['quantity'] = $qty,
                $cart_item['description'] = $description    
            );
            array_push($_SESSION['quotation'], $cart_item);
            echo '<script> window.location.href = "add-quotation.php"; </script>';
        }
    }else{ 
        //echo "<script>alert('Max quntity is '".$stockinfo['qty'].");</script>";
    }

}


?>