<?php
ob_start();
if(!isset($_SESSION)){ session_start(); } 

include 'load.php';

if(isset($_POST['save']))

{		







        $quotations_total = 0;
        $total = 0;

		$qnumber = $_POST['qnumber'];
		$date = $_POST['date'];
        $discount = $_POST['discount'];
        $fromcompany = $_POST['company'];
        $forcompanyaddress = $_POST['companyaddress'];
        $forcompanyphone = $_POST['companyphone'];
        $companyfor = $_POST['companyfor'];
        $companyaddressfor = $_POST['companyaddressfor'];
        $name = $_POST['name'];
        $account = $_POST['account'];
        $bank = str_replace("'","",$_POST['bank']);
        $branch = $_POST['branch'];
        $terms = $_POST['terms'];

        $due_date = $_POST['due_date'];
        $advance_payment = $_POST['advance_payment'];
        $emailfor = $_POST['emailfor'];
        $cpersonfor = $_POST['cpersonfor'];
        $validity_period = $_POST['validity_period'];
        $no_of_days = $_POST['no_of_days'];
        $companyemail = $_POST['companyemail'];
        $for_compny_phone = $_POST['companyphonefor']; 
        $pdf_title = $_POST['pdf_title'];
        $description = $_POST['description'];

        $imgFile = $_FILES['logo']['name'];
	    $tmp_dir = $_FILES['logo']['tmp_name'];
	    $imgSize = $_FILES['logo']['size'];
		

        $upload_dir = 'images/quotation/';

		$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); 

		
		$valid_extensions = array('jpeg', 'jpg', 'png'); 

		
		
		if ($imgSize > 0) {
			$userpic = rand(1, 1000000) . "." . $imgExt;
		}else{
			$userpic = "";
		}
		
		if (in_array($imgExt, $valid_extensions)) {
			
			if ($imgSize < 100000000) {
				move_uploaded_file($tmp_dir, $upload_dir . $userpic);
			} else {
				$errMSG = "Sorry, your file is too large.";
			}
		}

        if(!empty($userpic)){
            $imagename = $upload_dir.$userpic;
        }else{
            $imagename = "";
        }
       
        
        foreach ($_SESSION['quotation'] as $key => $cart_item) {
            $productid = $cart_item['product_id'];
            $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
            $quotations_total = $quotations_total+($cart_item['quantity']*$productinfo['price']);
        }
        $total = $quotations_total-$discount;


        $sql = "INSERT INTO tbl_quotations (quotations_no, date, Logo,discount,from_compay_name,from_compay_address,from_compay_phone,for_company_name,for_compny_address,bank_name,account_number,bank,branch,terms_and_condition,quotations_total,total,fromcompanyemail,emailfor,cpersonfor,no_of_days,validity_period,due_date,advance_payment,for_compny_phone,pdf_title,description)
            VALUES ('$qnumber', '$date', '$imagename', '$discount', '$fromcompany', '$forcompanyaddress', '$forcompanyphone', '$companyfor', '$companyaddressfor', '$name', '$account', '$bank','$branch', '$terms', '$quotations_total','$total','$companyemail','$emailfor','$cpersonfor','$no_of_days','$validity_period','$due_date','$advance_payment','$for_compny_phone','$pdf_title','$description')";

        

        if ($conn->query($sql) === TRUE) {
            $last_id = $conn->insert_id;

            foreach ($_SESSION['quotation'] as $key => $cart_item) {
                $productid = $cart_item['product_id'];
                $quantity = $cart_item['quantity'];
                $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
                $price = $productinfo['price'];
                $sql1 = "INSERT INTO tbl_quotations_items (product_id, quotations_id, qty,price)
                            VALUES ('$productid', '$last_id', '$quantity','$price')";
                if ($conn->query($sql1) === TRUE) {
                    unset($_SESSION['quotation']);
                    header("location: quotationList.php");
                }

            }

        }
	}

    $qnoinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_quotations ORDER BY quotations_id DESC LIMIT 1"));
   
    if(empty($qnoinfo)){
        $qno = "A1";
    }else{
        $quotations_no = $qnoinfo['quotations_no'];
        $str = substr($quotations_no, 1);
        $str = (int)$str+1;
        $qno = "A".(string)$str;
    }
        


?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="POS - Payroll | Pos & Invetory System | Dashboard
">
<meta name="keywords" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="author" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="robots" content="noindex, nofollow">

<title>Home | Payroll | Pos & Invetory System | Dashboard
</title>


<?php
require_once 'headercss.php';
?>
</head>
<body>
<div id="global-loader">
<div class="whirly-loader"> </div>
</div>

<div class="main-wrapper">
<?php
require_once 'header.php';
?>

<?php
require_once 'navbar.php';
?>

<div class="page-wrapper">
<div class="content">
<div class="page-header">
<div class="page-title">
<h4>Add Quotation / Invoice</h4>
<h6>Create new Quotation / Invoice</h6>
</div>
</div>


<div class="card">
    <div class="card-header">
        <div class="page-title">
            <h6 style="color: #fff;padding: 10px;">Add Items</h6>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>
<div class="card-body">
    <form method="POST" enctype="multipart/form-data" action="add-product-quotation.php">
    <div class="row">
        <div class="col-md-3">
                <div class="form-group">
                    <label>Product</label>
                    <select class="form-control select2" id="productlist" name="product" required>
                        <option value="">Select Product</option>
                        <?php $products = mysqli_query($conn, "SELECT * FROM mobileproducts"); 
                        
                            if ($products->num_rows > 0) {
                                while($row = $products->fetch_assoc()) {
                                    $productid = $row['prid'];
                                    $productname = $row['proname'];
                                    $stock = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$productid'"));
                                    if($stock['qty'] > 0){ ?>
                                        <option value="<?php echo $productid; ?>"><?php echo $productname; ?></option>
                                  <?php }
                                }
                            }
                        ?>
                    </select>
                    </div>
        </div>
        <div class="col-md-3">
                    <div class="form-group">
                        <label>Description</label>
                        <input type="text" name="description" class="form-control" id="description" placeholder="Description">
                    </div>
            </div>
            <div class="col-md-3">
                    <div class="form-group">
                        <label>Qty</label>
                        <input type="number" name="quntity" class="form-control" id="qty" placeholder="" required>
                    </div>
            </div>
            <div class="col-md-3">
                    <div class="form-group">
                        <label>Price</label>
                        <input type="text" class="form-control" id="price" placeholder="" readonly>
                    </div>
            </div>
            <div class="col-md-12 mb-4">
                    <button type="submit" class="btn btn-submit me-2">Add</button>
                        </form>
            </div>

    </div>
    <table class="table">
  <thead class="thead-dark">
    <tr>
      
      <th scope="col">Product</th>
      <th scope="col">Quantity</th>
      <th scope="col">Rate</th>
      <th scope="col">Amount</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php if(isset($_SESSION['quotation'])){ 
        foreach ($_SESSION['quotation'] as $key => $cart_item) {	
            $productid = $cart_item['product_id'];
            $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
            ?>
         <tr>
            <td><?php echo $productinfo['proname']; ?></td>
            <td><?php echo $cart_item['quantity']; ?></td>
            <td>Rs.<?php echo $productinfo['price']; ?></td>
            <td>Rs.<?php echo $cart_item['quantity']*$productinfo['price']; ?></td>
            <td><i style="cursor:pointer;" id="<?php echo $key; ?>" class="fa fa-trash delete"></i></td>
        </tr>
      <?php }

    } ?>
   
  
  </tbody>
</table>
</div>
</div>





<div class="card">
<div class="card-body">










<form method="POST" enctype="multipart/form-data">
<?php

if(isset($errMSG)){

?>
									
<div class="alert alert-danger border-0 bg-danger alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-message-square-x"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Error Alerts</h6>
<div class="text-white"> <?php echo $errMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}
	
else if(isset($successMSG)){

?>
									
<div class="alert alert-success border-0 bg-success alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-check-circle"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Success Alerts</h6>
<div class="text-white"><?php echo $successMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}

?>
        <div class="row">
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Quotation Number</label>
                            <input type="text" class="form-control" name="qnumber" value="<?php echo $qno; ?>" required>
                            
                        </div>

                </div>
                    <!--<div class="col-lg-3 col-sm-3 col-12">
                        <div class="form-group">
                                <label>Customer</label>
                                <select class="form-control" id="customers" name="customers">
                                    <option value="">Select Customer</option>
                                    <?php // $customers = mysqli_query($conn, "SELECT * FROM mobilecustomers"); 
                                    
                                        //if ($customers->num_rows > 0) {
                                        //    while($row = $customers->fetch_assoc()) {
                                        //        $coid = $row['coid'];
                                         //       $cname = $row['cname']; ?>
                                               
                                           //         <option value="<?php //echo $coid; ?>"><?php // echo $cname; ?></option>
                                          <?php 
// }
                                     //   }
                                    ?>
                                </select>
                        </div>
                    </div>-->
                    <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Date</label>
                            <input type="date" class="form-control" name="date" required>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Due Date</label>
                            <input type="date" class="form-control" name="due_date">
                            
                        </div>

                </div>
                
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Advance Payment</label>
                            <input type="number" class="form-control" name="advance_payment">
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Discount</label>
                            <input type="number" class="form-control" name="discount">
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Quotation Or Invoice</label>
                            <input type="text" class="form-control" name="pdf_title" required>
                            
                        </div>

                </div>
                <div class="col-lg-12 col-sm-12 col-12">
                    <hr>
                    <h4>Quotation For</h4>
                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Company name</label>
                            <input type="text" class="form-control" name="companyfor" required>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Company Address</label>
                            <input type="text" class="form-control" name="companyaddressfor">
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Phone Number</label>
                            <input type="text" class="form-control" name="companyphonefor" required>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Email Address</label>
                            <input type="email" class="form-control" name="emailfor">
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Contact Person</label>
                            <input type="text" class="form-control" name="cpersonfor">
                            
                        </div>

                </div>
                
               
                
                

                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Validity Period</label>
                            <input type="text" class="form-control" name="validity_period">
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>NO. of Days For Delivery</label>
                            <input type="number" class="form-control" name="no_of_days">
                            
                        </div>

                </div>

                <hr>
                
                <div class="col-lg-12 col-sm-12 col-12">
                    <hr>
                    <h4>Company Details</h4>
                    <?php 
                    $UserID=$_SESSION['user_id'];
                    $companyinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM branch,tbl_user_branch WHERE branch.branch_id=tbl_user_branch.branch_id AND tbl_user_branch.user_id='$UserID'"));
                    $bid = $companyinfo['branch_id'];
                    ?>
                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Company name</label>
                            <input type="text" class="form-control" name="company" value="<?php echo $companyinfo['branch_name']; ?>" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Company Address</label>
                            <input type="text" class="form-control" name="companyaddress" value="<?php echo $companyinfo['address']; ?>" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Phone Number</label>
                            <input type="text" class="form-control" name="companyphone"  value="<?php echo $companyinfo['phonenumbers']; ?>" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Email Address</label>
                            <input type="email" class="form-control" name="companyemail" value="<?php echo $companyinfo['email']; ?>" required readonly>
                            
                        </div>

                </div>
             <!--   <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Logo</label>
                            <input type="file" class="form-control" name="logo">
                            
                        </div>

                </div>-->
                <?php 
                    
                    $bankinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM bank_details WHERE branch_id='$bid'")); ?>
                <div class="col-lg-12 col-sm-12 col-12">
                    <hr>
                    <h4>Bank Details</h4>
                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Name</label>
                            <input type="text" class="form-control" name="name" value="<?php $banname = $bankinfo['name'] ?? '';  echo $banname; ?>" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Account Number</label>
                            <input type="number" class="form-control" value="<?php echo $bankinfo['account_number']; ?>" name="account" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Bank</label>
                            <input type="text" class="form-control" value="<?php $bank = $bankinfo['bank'] ?? ''; echo $bank; ?>" name="bank" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Branch</label>
                            <input type="text" class="form-control" value="<?php  $branch = $bankinfo['branch'] ?? ''; echo $branch; ?>" name="branch" required readonly>
                            
                        </div>

                </div>
                <div class="col-lg-12 col-sm-12 col-12">
                    <div class="form-group">
                        <?php $terms = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM terms_and_conditions WHERE branch_id='$bid'")); ?>
                        <label>Terms and condition</label>
                        <textarea class="form-control" name="terms" rows="3"><?php $terms = $terms['conditions'] ?? ''; echo $terms; ?></textarea>
                    </div>
                </div>
                <div class="col-lg-12">
                        <a href="#" class="btn btn-cancel">Cancel</a>
                        <button type="submit" name="save" class="btn btn-submit me-2">Save</button>
                </div>
        </div>
        </form>
        </div>
        </div>

        </div>
        </div>
        </div>


<script src="assets/js/jquery-3.6.0.min.js"></script>

<script src="assets/js/feather.min.js"></script>

<script src="assets/js/jquery.slimscroll.min.js"></script>

<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/dataTables.bootstrap4.min.js"></script>

<script src="assets/js/bootstrap.bundle.min.js"></script>

<script src="assets/plugins/select2/js/select2.min.js"></script>

<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>

<script src="assets/js/script.js"></script>

<script>
$(document).ready(function(){
    $('#productlist').on('change', function() {
       var productid = $(this).val();
        $.ajax({
           type: "POST",
           data: {productid:productid},
           dataType: "json",
           url: "quotation-change.php",
           success: function(data){
               $("#price").val(data[0]);
               $("#qty").attr("max",data[1]);
               $("#qty").attr("placeholder","Max Qty = "+data[1]);
           }
        });
    });

    $('.delete').on('click', function() {
        var key = $(this).attr('id');
        $.ajax({
           type: "POST",
           data: {key:key},
           url: "quotation-change.php",
           success: function(data){
            location.reload();
           }
        });
    });

    
      $(".select2").select2({
          
      });
});




</script>


</body>
</html>