<?php 
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');
$filepath = realpath(dirname(__FILE__));
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_3")
{
    require "../../inc/ajax_header.php";

    $seriNo = $commonFunctions->getRowDataCount('sys_erp_sales_invoice',''); 
    $seriNo1 = $commonFunctions->random_num(10 - strlen($seriNo));
    $invoice_no = "INV-".@$seriNo1.@$seriNo;

    $quotationData = $commonFunctions->getRowData('sys_erp_sales_quotation'," WHERE id = '".@$_GET['quotation_id']."' ");

     $last_id = $commonFunctions->addData('sys_erp_sales_invoice',"(invoice_no,invoice_date,invoice_due_date,branch,bill_to,ship_to,payment_mode,payment_terms,po_number,project_number,discount,tax_rate,sub_total,total,invoice_creator,delivery_note_flag,delivery_note_status,holder_name) VALUES ('".$invoice_no."','".$quotationData['quotation_date']."','".$quotationData['quotation_due_date']."','".$quotationData['branch']."','".$quotationData['bill_to']."','".$quotationData['bill_to']."','".$quotationData['payment_mode']."','".$quotationData['payment_terms']."','".$quotationData['po_number']."','".$quotationData['project_number']."','".$quotationData['discount']."','0','".$quotationData['sub_total']."','".$quotationData['total']."','".$quotationData['quotation_creator']."','".$quotationData['delivery_note_flag']."','".$quotationData['delivery_note_status']."','".$quotationData['delivery_note']."') ",'');
    if(!empty($last_id)){

        $commonFunctions->updateData('sys_erp_sales_quotation'," WHERE id = '".@$_GET['quotation_id']."' "," invoice_id='".(int)$last_id."', invoice_no='".$invoice_no."' ","");

        $data_array_details = array();

      $invoiceProductData = $commonFunctions->getData('sys_erp_sales_quotation_prdct_details'," WHERE quotation_id = '".@$_GET['quotation_id']."' "); 
      foreach ($invoiceProductData as $rw) 
      {
          //$data_array_details["invoice_id"] = $last_id;
          $data_array_details["invoice_no"] = $invoice_no;
          $data_array_details["product_id"] = $rw["product_id"];
          $data_array_details["unit_price"] = $rw["unit_price"];
          $data_array_details["quantity"] = $rw["quantity"];
          $data_array_details["product_desc"] = $rw["product_desc"];
          $data_array_details["total_amt"] = $rw["total_amt"];
          $commonFunctions->addData('sys_erp_sales_invoice_prdct_details'," (invoice_no,invoice_id,product_id,unit_price,quantity,total_amt,product_desc) VALUES ('".$invoice_no."','".$last_id."','".$rw['product_id']."','".$rw['unit_price']."','".$rw['quantity']."','".$rw['total_amt']."','".$rw['product_desc']."') ",'');

          $cond=" AND warehouse_id = '".$_SESSION["warehouse_id"]."' ";
          $cond=" AND product_id = '".$rw["product_id"]."' ";
          $getData1 = $commonFunctions->getData('invty_pdt_stock_mgt'," WHERE stock_id != 0 ".$cond);
          $iii = 0;
          $qty = $rw["quantity"];
          foreach ($getData1 as $rw) {
              if($iii == 0){    
                  $old_stock_count = $rw['stock_count'];
                  $stock_count = $old_stock_count - $qty;
                  //Deduction of stock
                  $commonFunctions->updateData('invty_pdt_stock_mgt'," WHERE stock_id = '".$rw["stock_id"]."' "," stock_count='".(int)$stock_count."' ","");
                  $iii = $iii + 1;
              }
          }
      }
    }
    Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <strong>Success !</strong> Wow, Quotation conveted to invoice Successfully !</div>');
    echo "quotation.php?state=list";
    exit();

}

if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_1"){
    require "../../inc/ajax_header.php";
    $added_by = $_SESSION['id'];
    $where = "";
    if(!empty($_POST['po_number'])){
      $where = " ,po_number='".$_POST['po_number']."' ";
    }
    $quotation_status = !empty($_POST['quotation_status'])?$_POST['quotation_status']:0;
    $last_id = $commonFunctions->updateData('sys_erp_sales_quotation'," WHERE id = '".$_POST['quotation_id']."' ","quotation_status = '".$quotation_status."' ".$where,"");

    Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <strong>Success !</strong> Wow, Your Information updated Successfully !</div>');
    echo "quotation-card.php?quotation_id=".$_POST['quotation_id'];
    exit();
    /*}else{
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<strong>Error !</strong> Data not inserted !</div>');
        echo "";
        exit();
    }*/
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_2"){
    require "../../inc/ajax_header.php";
    $commonFunctions->updateData('sys_erp_sales_quotation'," WHERE id = '".$_POST["quotation_id"]."'"," quotation_flag = 3 ","");
    Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <strong>Success !</strong> Wow, Your Information added Successfully !</div>');
    echo "quotation.php?state=list";
    exit();
}
require "../../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
$quotationData = $commonFunctions->getRowData('sys_erp_sales_quotation'," WHERE id = '".@$_GET['quotation_id']."' ");
?>

  <!-- Page-Title -->
  <div class="row">
      <div class="col-sm-12">
          <div class="page-title-box">
              <div class="row">
                  <div class="col form-row">
                      <div class="col-sm-5">
                          <h4 class="page-title">Quotation #<?php echo @$quotationData['quotation_no'];?></h4>
                          <ol class="breadcrumb">
                              <li class="breadcrumb-item"><a href="javascript:void(0);">Sales & Purchases</a></li>
                              <li class="breadcrumb-item"><a href="javascript:void(0);">Sales & Invoices</a></li>
                              <li class="breadcrumb-item"><a href="javascript:void(0);">Quotation #<?php echo @$quotationData['quotation_no'];?></a></li>
                          </ol>
                      </div>
                      <div class="col-sm-7" style="text-align: end;">
                          <!-- <a href="quotation.php?state=list"><button type="button" class="btn btn-sm btn-secondary clear_form">Back to Quotation List</button></a> -->

                          <div class="col-auto align-self-center">
                              <?php if(@$quotationData['quotation_flag'] != 4){ ?>                                 
                                  <a href="quotation.php?state=add&quotation_id=<?php echo $_GET['quotation_id'];?>" class="btn btn-secondary btn-sm">
                                      <i class="fas fa-edit align-self-center icon-xs"></i> Edit 
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-primary btn-sm" onclick='printDiv();'>
                                      <i class="fas fa-print align-self-center icon-xs"></i> Print
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-info btn-sm">
                                      <i class="fa fa-envelope-open align-self-center icon-xs"></i> Email
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-success btn-sm convert_to_invoice" >
                                      <i class="fa fa-file-invoice align-self-center icon-xs"></i> Convert to Invoice
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-danger btn-sm reject_quotation">
                                      <i class="fas fa-times-circle align-self-center icon-xs"></i> Reject
                                  </a>
                              <?php } ?>
                              <a href="quotation.php?state=list"><button type="button" class="btn btn-sm btn-secondary clear_form">Back to Quotation List</button></a>
                          </div>

                      </div>
                  </div><!--end col-->
              </div><!--end row-->                                                              
          </div><!--end page-title-box-->
      </div><!--end col-->
  </div><!--end row-->
  <!-- end page title end breadcrumb -->

  <div class="row">
      <div class="col-md-12">
          <div class="row card ">
              <div class="card-header2">
                  <?php echo !empty($msg)?$msg:''; ?>
              </div>
            <div class="card-body1 col-lg-12 mx-auto">
              <div class="card1" id="DivIdToPrint">
                 <div class="card-body invoice-head">
                    <div class="row">
                      <div class="col-md-5 align-self-center">    
                        <?php $orgData = $commonFunctions->getRowData("sys_erp_organaization",""); ?>
                        <?php $warehouseData = $commonFunctions->getRowData("invty_wrhus"," WHERE id='".$quotationData["branch"]."' "); ?>
                          <img src="<?php echo DOCUMENT_ROOT_CLASS;?>uploads/admin-setting/company/<?php echo @$orgData['erp_sys_org_logo'];?>" alt="logo-large" class="logo-lg logo-dark" height="80">  
                          <img src="<?php echo DOCUMENT_ROOT_CLASS;?>uploads/admin-setting/company/<?php echo @$orgData['erp_sys_org_logo'];?>" alt="logo-large" class="logo-lg logo-light" height="80"> 
                          <!--p class="mt-2 mb-0 text-muted">If account is not paid within 7 days the credits details supplied as confirmation.</p-->                                             
                      </div><!--end col-->    
                      <div class="col-md-7">                                                
                          <ul class="list-inline mb-0float-right">                                                   
                              <li class="list-inline-item">
                                  <div class="pl-3">
                                      <p class="text-muted mb-0"><?php echo @$warehouseData['address'];?></p>
                                      <p class="text-muted mb-0"><?php echo @$warehouseData['city'];?>, P.O.Box <?php echo @$warehouseData['zip_code'];?></p>
                                      <p class="text-muted mb-0">State of <?php echo $commonFunctions->getname(@$warehouseData['province'],"sys_erp_adm_countries_states","label","rowid");?></p>
                                  </div>                                                
                              </li>
                              <li class="list-inline-item">
                                  <div class="pl-3">
                                      <p class="text-muted mb-0">C.R # <?php echo @$orgData['erp_sys_org_cr_num'];?></p>
                                      <p class="text-muted mb-0" style="width: 300px;"><?php echo !empty(@$orgData['erp_sys_email_work'])?@$orgData['erp_sys_email_work']:"&nbsp;";?></p>
                                      <p class="text-muted mb-0"><?php echo @$orgData['erp_sys_org_phone_work'];?></p>
                                  </div>
                              </li>
                              <li class="list-inline-item">
                                  <div class="pl-1">
                                      <img alt='barcode' src='<?php echo DOCUMENT_ROOT_CLASS;?>lib/barcode.php?codetype=Code128&size=40&text=<?php echo @$quotationData['quotation_no'];?>&print=true'/>
                                  </div>
                              </li>
                          </ul>
                      </div><!--end col-->     
                  </div><!--end row--> 
                    <!--end row-->     
                 </div>
                 <!--end card-body-->
                 <div class="card-body">
                    <div class="row">
                       <div class="col-md-3">
                          <div class="float-left">
                             <address class="font-13">
                                <strong class="font-14">Billed To :</strong><br>
                                <?php $bcust = $commonFunctions->getRowData('crm_cust_details'," WHERE id = '".$quotationData['bill_to']."' ");
                                  echo $bcust['name'].'<br>'.$bcust['address'].','.$bcust['city'].' '.$bcust['postcode'].'<br>P: '.$bcust['phone']; ?>

                             </address>
                          </div>
                       </div>
                       <!--end col--> 
                       <div class="col-md-3">
                          
                       </div>
                       <!--end col-->
                       <div class="col-md-2">
                       </div>
                       <!--end col-->  
                       <div class="col-md-4">
                          <table id="" class="table table-bordered dt-responsive nowrap dataTable no-footer dtr-inline" style="border-collapse: collapse; border-spacing: 0px; width: 100%;" role="grid" aria-describedby="datatable_info">
                             <thead class="thead-light">
                                <tr>
                                   <th>Quotation Number :</th>
                                   <th><?php echo @$quotationData['quotation_no'];?></th>
                                </tr>
                                <!--end tr-->
                                <tr>
                                   <th>Quotation Date :</th>
                                   <th> <?php echo date("d M Y",strtotime(@$quotationData['quotation_date']));?>
                                   </th>
                                </tr>
                                <!--end tr-->
                                <tr>
                                   <th>Due Date :</th>
                                   <th> <?php echo date("d M Y",strtotime(@$quotationData['quotation_due_date']));?>
                                   </th>
                                </tr>
                                <!--end tr-->
                                <tr>
                                   <th>Delivery Note :</th>
                                   <th><span class="delivery_note"><?php echo @$quotationData['delivery_note'];?></span></th>
                                </tr>
                                <!--end tr-->
                             </thead>
                          </table>
                       </div>
                       <!--end col-->                       
                    </div>
                    <!--end row-->
                    <div class="row">
                       <div class="col-lg-12">
                          <div class="">
                             <table class="table table-bordered mb-0">
                                <thead class="thead-light">
                                   <tr>
                                      <th>PO Number</th>
                                      <th>Payment Mode</th>
                                      <th>Payment Type</th>
                                      <th>Project ID</th>
                                   </tr>
                                   <!--end tr-->
                                </thead>
                                <tbody>
                                   <tr>
                                      <td>CUS PO#<span class="cust_po"><?php echo @$quotationData['po_number'];?></span></td>
                                      <td><?php echo $commonFunctions->getname($quotationData['payment_mode'],'fin_accnt_payment_mode','label','id'); ?></td>
                                      <td><?php echo $commonFunctions->getname($quotationData['payment_terms'],'fin_accnt_payment_trems','label','id'); ?></td>
                                      <td>CUS PID#
                                        <?php echo @$quotationData['project_number'];?></td>
                                   </tr>
                                   <!--end tr-->
                                </tbody>
                             </table>
                             <!--end table-->
                          </div>
                          <!--end /div-->                                          
                       </div>
                       <!--end col-->                                      
                    </div>
                    <!--end row-->
                    <p></p>
                    <div class="row">
                       <div class="col-lg-12">
                          <div class="">
                             <table class="table table-bordered mb-0">
                                <thead class="thead-light">
                                   <tr>
                                      <th>Product Ref / ID</th>
                                      <th>Product Description</th>
                                      <th>Unit Price</th>
                                      <th>Quantity</th>
                                      <th>Total</th>
                                   </tr>
                                   <!--end tr-->
                                </thead>
                                <tbody>
                                  <?php $invoiceProductData = $commonFunctions->getData('sys_erp_sales_quotation_prdct_details'," WHERE quotation_id = '".@$_GET['quotation_id']."' "); 
                                  foreach ($invoiceProductData as $rw) {
                                  ?>
                                     <tr class="after-add-more">
                                        <td>
                                          <label class="form-control"> <?php echo $commonFunctions->getname($rw['product_id'],'invty_pdt_details','label','id'); ?></label>
                                        </td>
                                        <td>
                                          <label class="form-control"> <?php echo $rw['product_desc']; ?></label>
                                        </td>
                                        <td>
                                          <label class="form-control"> <?php echo $rw['unit_price']; ?></label>
                                        </td>
                                        <td>
                                          <label class="form-control"> <?php echo $rw['quantity']; ?></label>
                                        </td>
                                        <td>
                                          <label class="form-control"> <?php echo $rw['total_amt']; ?></label>
                                          <!-- <input type="text" name="total_pro_amt[]" class="total_pro_amt form-control total_pro_amt1" readonly=""> -->
                                        </td>
                                        
                                     </tr>
                                   <?php } ?>
                                   <!--end tr-->
                                   <tr>
                                      <td colspan="3" class="border-0"></td>
                                      <td class="border-0 font-14 text-dark"><b>Sub Total</b></td>
                                      <td class="border-0 font-14 text-dark"><b>
                                        <input type="hidden" name="sub_total_amt" class="sub_total_amt" value="0">
                                        <span class="sub_total_amt"><?php echo @$quotationData['sub_total'];?></span></b></td>
                                   </tr>
                                   <!--end tr-->
                                   <tr>
                                      <th colspan="3" class="border-0"></th>
                                      <td class="border-0 font-14 text-dark"><b>Tax Rate</b></td>
                                      <td class="border-0 font-14 text-dark"><b>$0.00%</b></td>
                                   </tr>
                                   <!--end tr-->
                                   <tr>
                                      <th colspan="3" class="border-0"></th>
                                      <td class="border-0 font-14 text-dark"><b>Discount</b></td>
                                      <td class="border-0 font-14 text-dark"><b><label class="form-control"><?php echo @$quotationData['discount'];?></label></b></td>
                                   </tr>
                                   <!--end tr-->
                                   <tr class="bg-black text-white">
                                      <th colspan="3" class="border-0"></th>
                                      <td class="border-0 font-14"><b>Total</b></td>
                                      <td class="border-0 font-14"><b><label class="form-control"><?php echo @$quotationData['total'];?></label></b></td>
                                   </tr>
                                   <!--end tr-->
                                </tbody>
                             </table>
                             <!--end table-->
                          </div>
                          <!--end /div-->                                          
                       </div>
                       <!--end col-->                                      
                    </div>
                    <!--end row-->
                    <div class="row justify-content-center">
                       <div class="col-lg-6">
                          <h5 class="mt-4">Terms And Condition :</h5>
                          <ul class="pl-3">
                             <li><small class="font-12">All accounts are to be paid within 7 days from receipt of invoice. </small></li>
                             <li><small class="font-12">To be paid by cheque or credit card or direct payment online.</small></li>
                             <li><small class="font-12"> If account is not paid within 7 days the credits details supplied as confirmation of work undertaken will be charged the agreed quoted fee noted above.</small></li>
                          </ul>
                       </div>
                       <!--end col-->                                       
                       <div class="col-lg-6 align-self-end">
                          <div class="float-right" style="width: 30%;">
                             <small>Account Manager</small>
                             <img src="assets/images/signature.png" alt="" class="mt-2 mb-1" height="26">
                             <p class="border-top">Signature</p>
                          </div>
                       </div>
                       <!--end col-->
                    </div>
                    <!--end row-->
                    <hr>
                    <div class="row d-flex justify-content-center">
                       <div class="col-lg-12 col-xl-4 ml-auto align-self-center">
                          <div class="text-center"><small class="font-12">Thank you very much for doing business with us.</small></div>
                       </div>
                       <!--end col-->
                       <div class="col-lg-12 col-xl-8">
                          <div class="float-right d-print-none">
                             <div class="col-auto align-self-center"> 
                              <?php if(@$quotationData['quotation_flag'] != 4){ ?>                                 
                                  <a href="quotation.php?state=add&quotation_id=<?php echo $_GET['quotation_id'];?>" class="btn btn-secondary btn-sm">
                                      <i class="fas fa-edit align-self-center icon-xs"></i> Edit 
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-primary btn-sm" onclick='printDiv();'>
                                      <i class="fas fa-print align-self-center icon-xs"></i> Print
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-info btn-sm">
                                      <i class="fa fa-envelope-open align-self-center icon-xs"></i> Email
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-success btn-sm convert_to_invoice">
                                      <i class="fa fa-file-invoice align-self-center icon-xs"></i> Convert to Invoice
                                  </a>
                                  <a href="javascript:void(0);" class="btn btn-danger btn-sm reject_quotation">
                                      <i class="fas fa-times-circle align-self-center icon-xs"></i> Reject
                                  </a>
                              <?php } ?>
                              <a href="quotation.php?state=list"><button type="button" class="btn btn-sm btn-secondary clear_form">Back to Quotation List</button></a>
                          </div>
                            <!-- <a href="quotation.php?state=list"><button type="button" class="btn btn-sm btn-secondary clear_form"><< Back to Quotation List</button></a> -->
                            <!-- <button type="button" class="btn btn-soft-success btn-sm" id="save_form">
                            <i class="fa fa-file-invoice align-self-center icon-xs"></i> Create Quotation
                            </button> -->
                          </div>
                       </div>
                       <!--end col-->
                    </div>
                    <!--end row-->
                 </div>
                 <!--end card-body-->
              </div>
              <!--end card-->
            </div>
             <!--end col-->
          </div>  
      </div><!--end col-->
  </div><!--end row-->
  
<?php require "../../inc/footer.php"; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script type="text/javascript">
function printDiv(){
  var printContents = document.getElementById('DivIdToPrint').innerHTML;
  var originalContents = document.body.innerHTML;
  document.body.innerHTML = printContents;
  window.print();
  document.body.innerHTML = originalContents;
}
function printDiv1()
{
  var divToPrint=document.getElementById('DivIdToPrint');
  var newWin=window.open('','Print-Window');
  newWin.document.open();
  newWin.document.write('<html><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/css/common.css" rel="stylesheet" type="text/css" /><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/plugins/leaflet/leaflet.css" rel="stylesheet"><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/plugins/lightpick/lightpick.css" rel="stylesheet" /><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" /><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/css/icons.min.css" rel="stylesheet" type="text/css" /><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/css/app.min.css" rel="stylesheet" type="text/css" /><link href="<?php echo DOCUMENT_ROOT_CLASS;?>assets/plugins/treeview/themes/default/style.css" rel="stylesheet"><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
  newWin.document.close();
  setTimeout(function(){newWin.close();},10);
}
$(".save_form").click(function(){
  $("#quotation_form").validate();  
    if($("#quotation_form").valid()){
        $.ajax({
            type: 'POST',
            url: "",
            data: $('#quotation_form').serialize()+"&action=ajax_call_1",
            success: function(response) { 
            window.location.href = response;
            }
        });
    }
});
$(".reject_quotation").click(function(){
    if(confirm("Please make sure do you want to reject ?")){
        $.ajax({
            type: 'POST',
            url: "",
            data: "quotation_id=<?php echo $_GET['quotation_id'];?>&action=ajax_call_2",
            success: function(response) { 
              window.location.href = response;
            }
        });
    }
});
$(".convert_to_invoice").click(function(){
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be convert to invoice!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, convert it!'
  }).then((result) => {
    if (result.isConfirmed) 
    {
        $.ajax({
            type: 'POST',
            url: "",
            data: "quotation_id=<?php echo $_GET['quotation_id'];?>&action=ajax_call_3",
            success: function(response) { 
              Swal.fire(
                'Invoice Converted!',
                'Your invoice has been coverted.',
                'success'
              );
              window.location.href = response;
            }
        });
        /*Swal.fire({
          title: 'Invoice Converted!', 
          text: 'Your invoice has been coverted.', 
          icon: 'success',
          showCancelButton: false,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Ok'
        }).then((result1) => {
          //if (result1.isConfirmed) {
            //window.location.href="invoice.php?state=list";
          }//

          alert('success');

        });*/    
    }    
  })
});
</script>
