<?php 
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');

$filepath = realpath(dirname(__FILE__));
require "../../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
if(!empty($_GET['action']) and @$_GET['action'] == "export"){
    @unlink('../../uploads/product-services/product-images/Products-Details-List.xls');
    require('../../lib/PHPExcel-1.8/Classes/PHPExcel.php');
    require_once '../../lib/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle('Products Details List');
    
    ob_start();
    $objPHPExcel->setActiveSheetIndex(0); // Create new worksheet
    $head = 0;
    $table_head = array("Label / Product Name","Product Ref#","Barcode Value","Selling Price","Physical Stock","Virtual Stock","Product Description");
    foreach($table_head as $value)
    {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($head, 2, $value);   
        $head++;
    }
    $firstRowData = "Products Details List";

    $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:G1');
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, $firstRowData);
    
    $body = 3;//Add some data
    $export_data = $commonFunctions->getData('invty_pdt_details', "");
    foreach($export_data as $row)
    {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,$body,$row['label']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,$body,$row['reference_number']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,$body,$row['barcode_value']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3,$body,$row['price']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4,$body,$row['virtual_stock']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5,$body,$row['physical_stock']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6,$body,$row['description']);
        $body++;
    }
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    // If you want to output e.g. a PDF file, simply do:
    $objWriter->save('../../uploads/product-services/product-images/Products-Details-List.xls');
    echo "<script>window.open('../../uploads/product-services/product-images/Products-Details-List.xls');</script>";
}
?>

    <!-- Page-Title -->
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <h4 class="page-title"><?php echo ($_GET['state'] != "list")?"Add Products":"Product List"; ?></h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Products & Services</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Products</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo ($_GET['state'] != "list")?"Add Products":"Product List"; ?></a></li>
                        </ol>
                    </div><!--end col-->
                    <div class="col-auto align-self-center">
                        <!-- <button type="button" class="btn btn-sm btn-outline-primary">
                            <i class="align-self-center ti-export"></i>
                        </button> -->
                        <?php if(@$_GET['state'] == "list"){ ?>
                            <a href="product.php?state=<?php echo $_GET['state'];?>&action=export" class="btn btn-sm btn-outline-primary">
                                <i data-feather="download" class="align-self-center icon-xs"></i> Download Product List
                            </a>
                            
                            <a href="import-product.php" class="btn btn-sm btn-outline-dark">
                                <i data-feather="upload" class="align-self-center icon-xs"></i> Import Product List
                            </a>
                        <?php }else{ ?>
                            <button type="button" class="btn btn-sm btn-outline-primary save_form">Save</button>
                            <button type="button" class="btn btn-sm btn-outline-danger clear_form">Clear</button>
                            <a href="product.php?state=list"><button type="button" class="btn btn-sm btn-outline-secondary clear_form">Back to Products List</button></a>
                        <?php } ?>
                    </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-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"> 
                        <div class="form-row">
                            <div class="form-group searchForm col-md-6">    
                                <a class="btn btn-soft-primary" href="product.php?state=add" role="button" ><i class="fas fa-plus mr-2"></i> Add New Product</a>
                            </div>  
                            <div class="form-group searchForm col-md-6">
                                <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                                <form action="" id="searchForm" method="GET">
                                    <div class="form-row">
                                        <div class="form-group searchForm col-md-8">
                                            <input type="text" name="search" id="search" placeholder="Search" class="form-control" value="<?php echo @$_GET['search']; ?>">
                                            <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
                                            <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>">
                                        </div>
                                        <div class="form-group searchForm col-md-4">
                                            <button type="submit" id="searchbtn" class="btn btn-primary"> <i class="fa fa-search"></i> Search</button>
                                            <button type="button" id="clearbtn" class="btn btn-danger"> <i class="fa fa-trash"></i> Clear</button>
                                        </div>
                                    </div>
                                </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </h4>
                    <?php echo !empty($msg)?$msg:''; ?>        
                </div>
       
                <div class="card-body">
                    <div class="row">
                        <?php if(@$_GET['state'] != "list"): ?>
                            <?php 
                            $error_ = 0;
                                if(@$_GET['product_id'] != ''){
                                    $editData = $commonFunctions->getRowData('invty_pdt_details'," WHERE id = '".$_GET['product_id']."' ");
                                }
                                if(!empty($_POST)){
                                    $id = (!empty($_GET['product_id']) and @$_GET['state']== "edit")?$_GET['product_id']:0;
                                    if(empty($_POST['label'])){
                                        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> Please enter label !</div>');
                                    }
                                    if(empty($_POST['reference_number'])){
                                        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> Please enter reference number!</div>');
                                        echo "<script>window.location.href='';</script>";
                                    }else{
                                        $cntA = $commonFunctions->getRowData('invty_pdt_details',' WHERE reference_number = "'.$_POST['reference_number'].'" and `id` NOT IN ('.$id.') ');
                                        if(@count($cntA) > 1){
                                           $error_ = 1;
                                           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>Reference number already exists !</div>');
                                        }
                                    }
                                    if(!empty($_POST['barcode_value'])){
                                        $cntA1 = $commonFunctions->getRowData('invty_pdt_details',' WHERE barcode_value = "'.$_POST['barcode_value'].'" and `id` NOT IN ('.$id.') ');
                                        if(@count($cntA1) > 1){
                                           $error_ = 1;
                                           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>Barcode value already exists !</div>');
                                        }
                                    }
                                    if(!empty($_POST['label']) and $error_ == 0){
                                        $added_by = $_SESSION['id'];
                                        if(empty($_POST['product_id'])){
                                            $column = $fileName = "";
                                            if($_FILES["product_images"]){
                                                $target_dir = "../../uploads/product-services/product-images/";
                                                $target_file = $target_dir . $_POST['reference_number']."-".basename($_FILES["product_images"]["name"]);
                                                $uploadOk = 1;
                                                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                                                $target_file = $target_dir . $_POST['reference_number'].".".$imageFileType;
                                                @getimagesize($_FILES["product_images"]["tmp_name"]);
                                                if(move_uploaded_file($_FILES["product_images"]["tmp_name"], $target_file)){
                                                    $column = " ,product_images";
                                                    $fileName = " , '".$_POST['reference_number'].".".$imageFileType."'";
                                                }
                                            }
                                            $commonFunctions->addData('invty_pdt_details'," (product_type,reference_number,label,sales_status,purchase_status,lot_serial_status,barcode_type,barcode_value,description,public_url,default_warehouse_id,stock_limit_alert,desired_optimal_stock,nature,weight,weight_units_id,size_length,size_width,size_height,surface,surface_unit_id,volume,volume_unit_id,customcode,country_id,note,tag_id,price,price_base_type,min_price,tax_management_id,accountancy_code_sell,accountancy_code_purchase,duration,duration_type,buying_price,cost_price,selling_type,added_by,virtual_stock,physical_stock ".$column.") VALUES ('".$_POST['product_type']."','".$_POST['reference_number']."','".$_POST['label']."','".$_POST['sales_status']."','".$_POST['purchase_status']."','".$_POST['lot_serial_status']."','".$_POST['barcode_type']."','".$_POST['barcode_value']."','".$_POST['description']."','".$_POST['public_url']."','".$_POST['default_warehouse_id']."','".$_POST['stock_limit_alert']."','".$_POST['desired_optimal_stock']."','".$_POST['nature']."','".$_POST['weight']."','".$_POST['weight_units_id']."','".$_POST['size_length']."','".$_POST['size_width']."','".$_POST['size_height']."','".$_POST['surface']."','".$_POST['surface_unit_id']."','".$_POST['volume']."','".$_POST['volume_unit_id']."','".$_POST['customcode']."','".$_POST['country_id']."','".$_POST['note']."','".$_POST['tag_id']."','".$_POST['price']."','".$_POST['price_base_type']."','".$_POST['min_price']."','".$_POST['tax_management_id']."','".$_POST['accountancy_code_sell']."','".$_POST['accountancy_code_purchase']."','".$_POST['duration']."','".$_POST['duration_type']."','".$_POST['buying_price']."','".$_POST['cost_price']."','".$_POST['selling_type']."','".$added_by."','".$_POST['virtual_stock']."','".$_POST['physical_stock']."'".$fileName.") ",'product.php?state=add');
                                        }else{
                                            $column = $fileName = "";
                                            if($_FILES["product_images"]){
                                                $target_dir = "../../uploads/product-services/product-images/";
                                                $target_file = $target_dir . $_POST['reference_number']."-".basename($_FILES["product_images"]["name"]);
                                                $uploadOk = 1;
                                                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                                                $target_file = $target_dir . $_POST['reference_number'].".".$imageFileType;
                                                @getimagesize($_FILES["product_images"]["tmp_name"]);
                                                if(move_uploaded_file($_FILES["product_images"]["tmp_name"], $target_file)){
                                                    $column = " ,product_images";
                                                    $fileName = " ,product_images = '".$_POST['reference_number'].".".$imageFileType."' ";
                                                }
                                            }
                                            $updated_by = $_SESSION['id'];
                                            $commonFunctions->updateData('invty_pdt_details'," WHERE id = '".$_POST['product_id']."' ", " product_type = '".$_POST['product_type']."',reference_number='".$_POST['reference_number']."', label='".$_POST['label']."' , sales_status='".$_POST['sales_status']."' , purchase_status='".$_POST['purchase_status']."' , lot_serial_status='".$_POST['lot_serial_status']."' , barcode_type='".$_POST['barcode_type']."' , barcode_value='".$_POST['barcode_value']."', description='".$_POST['description']."', public_url='".$_POST['public_url']."', default_warehouse_id='".$_POST['default_warehouse_id']."', stock_limit_alert='".$_POST['stock_limit_alert']."', desired_optimal_stock='".$_POST['desired_optimal_stock']."', nature='".$_POST['nature']."', weight='".$_POST['weight']."', weight_units_id='".$_POST['weight_units_id']."', size_length='".$_POST['size_length']."', size_width='".$_POST['size_width']."', size_height='".$_POST['size_height']."', surface='".$_POST['surface']."', volume_unit_id='".$_POST['volume_unit_id']."', customcode='".$_POST['customcode']."', country_id='".$_POST['country_id']."', note='".$_POST['note']."', tag_id='".$_POST['tag_id']."', price='".$_POST['price']."', price_base_type='".$_POST['price_base_type']."', min_price='".$_POST['min_price']."', tax_management_id='".$_POST['tax_management_id']."', accountancy_code_sell='".$_POST['accountancy_code_sell']."', accountancy_code_purchase='".$_POST['accountancy_code_purchase']."', duration='".$_POST['duration']."', duration_type='".$_POST['duration_type']."', buying_price='".$_POST['buying_price']."', cost_price='".$_POST['cost_price']."', selling_type='".$_POST['selling_type']."', virtual_stock='".$_POST['virtual_stock']."', physical_stock='".$_POST['physical_stock']."', updated_by='".$updated_by."'".$fileName,'product.php?state=list');
                                        }
                                    }
                                }
                            ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card">
                                    <div class="card-body"-->
                                        <form id="product_form" action="" method="post" enctype="multipart/form-data">
                                            <input type="hidden" name="product_id" value="<?php echo ($_GET['state'] == 'edit')?@$_GET['product_id']:0;?>">

                                            <input type="hidden" name="product_type" value="1">
                                            <div class="form-row">
                                                <!-- <div class="col-md-6 position-relative form-group">
                                                    <label for="product_type" class="">Product Type</label>
                                                    <select class="form-control" name="product_type" id="product_type">
                                                        <option value="0"></option>
                                                        <option value="1" <?php echo (@$editData['product_type'] == 1)?"selected":"";?> >Product</option>
                                                        <option value="2" <?php echo (@$editData['product_type'] == 2)?"selected":"";?> >Service</option>
                                                    </select>
                                                </div> -->

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="label" class="">Label / Product Name <span class="error">*</span></label>
                                                    <input name="label" id="label" placeholder="Please enter label" type="text" class="form-control" value="<?php echo @$editData['label'];?>" required="">
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="sales_status" class="">Sales Status</label>
                                                    <select class="form-control" name="sales_status" id="sales_status">
                                                        <option value="1" <?php echo (@$editData['sales_status'] == 1)?"selected":"";?> >For Sale</option>
                                                        <option value="0" <?php echo (!empty($editData) and @$editData['sales_status'] == 0)?"selected":"";?> >Not For Sale</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="purchase_status" class="">Purchase Status</label>
                                                    <select class="form-control" name="purchase_status" id="purchase_status">
                                                        <option value="1" <?php echo (@$editData['purchase_status'] == 1)?"selected":"";?> >For Purchase</option>
                                                        <option value="0" <?php echo (!empty($editData) and @$editData['purchase_status'] == 0)?"selected":"";?> >Not For Purchase </option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="lot_serial_status" class="">Use Lot / Serial Number </label>
                                                    <select class="form-control" name="lot_serial_status" id="lot_serial_status">
                                                        <option value="0" <?php echo (@$editData['lot_serial_status'] == 0)?"selected":"";?> >No ( Lot / Serial not Used )</option>
                                                        <option value="1" <?php echo (@$editData['lot_serial_status'] == 1)?"selected":"";?> >Yes ( Lot / Serial Required )</option>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="barcode_type" class="">Barcode Type</label>
                                                    <select class="form-control" name="barcode_type" id="barcode_type">
                                                        <option value=""></option>
                                                        <?php
                                                        $barcodeArr = $commonFunctions->getData('sys_erp_adm_barcode_type',' WHERE active = 1 ');
                                                        foreach ($barcodeArr as $row) { ?>
                                                            <option value="<?php echo $row['id'];?>" <?php echo (@$editData['barcode_type'] == $row['id'])?"selected":"";?> ><?php echo $row['label']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="reference_number" class="">Reference Number <span class="error">*</span></label>
                                                    <input name="reference_number" id="reference_number" placeholder="Please enter reference number" type="text" class="form-control" value="<?php echo @$editData['reference_number'];?>" required="">
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="barcode_value" class="">Barcode Value</label>
                                                    <input name="barcode_value" id="barcode_value" placeholder="Please enter barcode value" type="text" class="form-control" value="<?php echo @$editData['barcode_value'];?>" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="description" class="">Description</label>
                                                    <textarea name="description" class="form-control"><?php echo @$editData['description'];?></textarea>
                                                </div>
                                                
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="default_warehouse_id" class="">Default Warehouse</label>
                                                    <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                                                    <select class="form-control" name="default_warehouse_id" id="default_warehouse_id">
                                                        <option value="0"></option>
                                                        <?php foreach ($warehouseData as $rw) { ?>
                                                            <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['default_warehouse_id'] == $rw['id'])?"selected":"";?> ><?php echo $rw['short_name_location']; ?></option>     
                                                        <?php } ?>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="stock_limit_alert" class="">Stock Limit for Alert</label>
                                                    <input name="stock_limit_alert" id="stock_limit_alert" placeholder="Please enter stock limit alert" type="text" class="form-control" value="<?php echo (empty(@$editData['stock_limit_alert']))?0:@$editData['stock_limit_alert'];?>">
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="desired_optimal_stock" class="">Desired Optimal Stock</label>
                                                    <input name="desired_optimal_stock" id="desired_optimal_stock" placeholder="Please enter stock limit alert" type="text" class="form-control" value="<?php echo (empty(@$editData['desired_optimal_stock']))?0:@$editData['desired_optimal_stock'];?>">
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="nature" class="">Nature</label>
                                                    <select class="form-control" name="nature" id="nature">
                                                        <option value="0"></option>
                                                        <option value="0" <?php echo (@$editData['nature'] == 0)?"selected":"";?> >Raw Material</option>
                                                        <option value="1" <?php echo (@$editData['nature'] == 1)?"selected":"";?> >Manufactured Product</option>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="note" class="">Note (not visible on Invoices, Proposals...)</label>
                                                    <textarea name="note" class="form-control"><?php echo @$editData['note'];?></textarea>
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="tag_id" class=""> Tags / Categories </label>
                                                    <?php $TagData = $commonFunctions->getData('invty_pdt_tag',''); ?>
                                                    <select name="tag_id" id="tag_id" class="form-control select2" >
                                                        <option value="0">Select</option>
                                                        <?php foreach ($TagData as $rw) { ?>
                                                            <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['tag_id'] == $rw['id'])?"selected":"";?> ><?php 
                                                            if($rw['parent_id'] > 0){
                                                                echo $commonFunctions->getName($rw['parent_id'],'crm_cust_tag','label','id')." >> ";           
                                                            }
                                                            echo $rw['label']; ?></option>     
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="price" class="">Selling Price </label>
                                                    <div style="display: flex;">   
                                                        <input name="price" id="price" placeholder="Please enter price" type="text" class="form-control" value="<?php echo (empty(@$editData['price']))?0:@$editData['price'];?>" style="width:70%">
                                                        <select class="form-control" name="price_base_type" id="price_base_type"  style="width:30%">
                                                            <option value=""></option>
                                                            <option value="HT" <?php echo (@$editData['nature'] == "HT")?"selected":"";?> >Net of TAX</option>
                                                            <option value="TTC" <?php echo (@$editData['nature'] == "TTC")?"selected":"";?> >Inc. TAX</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="min_price" class="">Min. Selling Price</label>
                                                    <input name="min_price" id="min_price" placeholder="Please enter min price" type="text" class="form-control" value="<?php echo (empty(@$editData['min_price']))?0:@$editData['min_price'];?>" >
                                                </div>

                                                <div class="position-relative form-group col-md-4">
                                                    <label for="tax_management_id" class=""> VAT Rate   </label>
                                                    <select id="tax_management_id" name="tax_management_id" class="flat tax_management_id form-control">
                                                        <option value="0"></option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="duration" class="">Duration </label>
                                                    <div style="display: flex;">   
                                                        <input name="duration" id="duration" placeholder="Please enter duration" type="text" class="form-control" value="<?php echo @$editData['duration'];?>" style="width:70%">
                                                        <select class="form-control" name="duration_type" id="duration_type"  style="width:30%">
                                                            <option value=""></option>
                                                            <option value="i" <?php echo (@$editData['nature'] == "i")?"selected":"";?> >I</option>
                                                            <option value="h" <?php echo (@$editData['nature'] == "h")?"selected":"";?> >H</option>
                                                            <option value="d" <?php echo (@$editData['nature'] == "d")?"selected":"";?> >D</option>
                                                            <option value="w" <?php echo (@$editData['nature'] == "w")?"selected":"";?> >W</option>
                                                            <option value="m" <?php echo (@$editData['nature'] == "m")?"selected":"";?> >M</option>
                                                            <option value="y" <?php echo (@$editData['nature'] == "y")?"selected":"";?> >Y</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="selling_type" class="">Selling Type</label>
                                                    <select class="form-control" name="selling_type" id="selling_type">
                                                        <option value="0"></option>
                                                        <option value="0" <?php echo (@$editData['selling_type'] == 0)?"selected":"";?> >Fixed Amount</option>
                                                        <option value="1" <?php echo (@$editData['selling_type'] == 1)?"selected":"";?> >Recurring Amount</option>
                                                    </select>
                                                </div>
                                                <div class="position-relative form-group col-md-4">
                                                    <label for="assigned_to_sales" class=""> Product Image </label><br>
                                                    <input type="file" name="product_images" id="product_image">
                                                </div>

                                                <div class="col-md-12 position-relative form-group">
                                                    <div class="accordion" id="accordionExample">
                                                        <div class="card border mb-1 shadow-none">
                                                            <a href="" id="expand" class="text-dark collapsed" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
                                                                <div class="card-header rounded-0" id="headingOne">
                                                                    Advanced Features 
                                                                    <span class="accordion-class" style="float: right;font-size: 20px;font-family: 'Roboto';">
                                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-menu align-self-center topbar-icon"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
                                                                    </span>
                                                                </div>
                                                            </a>
                                                            <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample" style="">
                                                                <div class="card-body form-row">
                                                                    <input type="hidden" name="accordioninput" id="accordioninput" value="0">
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="buying_price" class="">Buying Price</label>
                                                                        <input name="buying_price" id="buying_price" placeholder="Please enter buying price" type="text" class="form-control" value="<?php echo (empty(@$editData['buying_price']))?0:@$editData['buying_price'];?>" >
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="cost_price" class="">Cost Price</label>
                                                                        <input name="cost_price" id="cost_price" placeholder="Please enter buying price" type="text" class="form-control" value="<?php echo (empty(@$editData['cost_price']))?0:@$editData['cost_price'];?>" >
                                                                    </div>
                                                                    
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="public_url" class="">Public URL</label>
                                                                        <input name="public_url" id="public_url" placeholder="Please enter public url" type="text" class="form-control" value="<?php echo @$editData['public_url'];?>">
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="weight" class="">Weight</label>
                                                                        <div style="display: flex;">   
                                                                            <input name="weight" id="weight" placeholder="Please enter stock limit alert" type="text" class="form-control" value="<?php echo @$editData['weight'];?>" style="width:70%">
                                                                            <select class="form-control" name="weight_units_id" id="weight_units_id"  style="width:30%">
                                                                                <option value="0"></option>
                                                                                <?php
                                                                                $barcodeArr = $commonFunctions->getData('invty_pdt_weight_units',' WHERE active = 1 ');
                                                                                foreach ($barcodeArr as $row) { ?>
                                                                                    <option value="0" <?php echo (@$editData['weight_units_id'] == $row['id'])?"selected":"";?> ><?php echo $row['label']; ?></option>
                                                                                <?php } ?>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="weight" class="">Length x Width x Height</label>
                                                                        <div style="display: flex;">   
                                                                            <input name="size_length" id="size_length" placeholder="Please enter size" type="text" class="form-control" value="<?php echo (empty(@$editData['size_length']))?0:@$editData['size_length'];?>" style="width:30%">
                                                                            <input name="size_width" id="size_width" placeholder="Please enter width" type="text" class="form-control" value="<?php echo (empty(@$editData['size_width']))?0:@$editData['size_width'];?>" style="width:30%">
                                                                            <input name="size_height" id="size_height" placeholder="Please enter stock size height" type="text" class="form-control" value="<?php echo (empty(@$editData['size_height']))?0:@$editData['size_height'];?>" style="width:30%">
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="surface" class="">Area</label>
                                                                        <div style="display: flex;">   
                                                                            <input name="surface" id="surface" placeholder="Please enter surface" type="text" class="form-control" value="<?php echo (empty(@$editData['surface']))?0:@$editData['surface'];?>" style="width:70%">
                                                                            <select class="form-control" name="surface_unit_id" id="surface_unit_id"  style="width:30%">
                                                                                <option value="0"></option>
                                                                                <?php
                                                                                $barcodeArr = $commonFunctions->getData('invty_pdt_surface_units',' WHERE active = 1 ');
                                                                                foreach ($barcodeArr as $row) { ?>
                                                                                    <option value="0" <?php echo (@$editData['surface_unit_id'] == $row['id'])?"selected":"";?> ><?php echo $row['label']; ?></option>
                                                                                <?php } ?>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="volume" class="">Volume</label>
                                                                        <div style="display: flex;">   
                                                                            <input name="volume" id="volume" placeholder="Please enter volume" type="text" class="form-control" value="<?php echo (empty(@$editData['volume']))?0:@$editData['volume'];?>" style="width:70%">
                                                                            <select class="form-control" name="volume_unit_id" id="volume_unit_id"  style="width:30%">
                                                                                <option value="0"></option>
                                                                                <?php
                                                                                $barcodeArr = $commonFunctions->getData('invty_pdt_volume_units',' WHERE active = 1 ');
                                                                                foreach ($barcodeArr as $row) { ?>
                                                                                    <option value="0" <?php echo (@$editData['volume_unit_id'] == $row['id'])?"selected":"";?> ><?php echo $row['label']; ?></option>
                                                                                <?php } ?>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="customcode" class="">Customs / Commodity / HS Code </label>
                                                                        <input name="customcode" id="customcode" placeholder="Please enter Customs / Commodity / HS Code" type="text" class="form-control" value="<?php echo @$editData['customcode'];?>">
                                                                    </div>
                                                                    <div class="col-md-4 form-group">
                                                                        <label for="country_id" class=""> Country of Origin</label>
                                                                        <?php $countryData = $commonFunctions->getData('sys_erp_adm_countries',' WHERE active = 1 '); ?>
                                                                        <select name="country_id" id="country_id" class=" select2 form-control" >
                                                                            <option value="0">Select Country</option>
                                                                            <?php foreach ($countryData as $rw) { ?>
                                                                                <option value="<?php echo $rw['rowid'];?>" <?php echo (@$editData['country_id'] == $rw['rowid'])?"selected":"";?> ><?php echo $rw['label']."(".$rw['code'].")"; ?></option>     
                                                                            <?php } ?>
                                                                        </select>
                                                                    </div>
                                                                    <div class="position-relative form-group col-md-4">
                                                                        <label for="accountancy_code_sell" class="">Accounting Code (Sale)</label>
                                                                        <select id="accountancy_code_sell" name="accountancy_code_sell" class="flat accountancy_code_sell form-control">
                                                                            <option value="0"></option>
                                                                        </select>
                                                                    </div>
                                                                    <div class="position-relative form-group col-md-4">
                                                                        <label for="accountancy_code_purchase" class="">Accounting Code (Purchase)</label>
                                                                        <select id="accountancy_code_purchase" name="accountancy_code_purchase" class="flat accountancy_code_purchase form-control">
                                                                            <option value="0"></option>
                                                                        </select>
                                                                    </div>

                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="virtual_stock" class="">Virtual Stock </label>
                                                                        <input name="virtual_stock" id="virtual_stock" placeholder="Please enter Virtual Stock" type="text" class="form-control" value="<?php echo @$editData['virtual_stock'];?>">
                                                                    </div>
                                                                    <div class="col-md-6 position-relative form-group">
                                                                        <label for="physical_stock" class="">Physical Stock </label>
                                                                        <input name="physical_stock" id="physical_stock" placeholder="Please enter Virtual Stock" type="text" class="form-control" value="<?php echo @$editData['physical_stock'];?>">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                    </div>
                                                </div>

                                                <div class="col-md-6 position-relative form-group">
                                                    <button type="submit" class="mt-1 btn btn-primary">Submit</button>
                                                </div>
                                            </div>
                                        </form>
                                    <!--/div>
                                </div-->
                            </div>
                        <?php else: ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card">
                                    <div class="card-body"-->
                                        <style type="text/css">
                                            tr {cursor: pointer;}
                                        </style>
                                        <?php 
                                        $targetpage = "product.php?state=list";
                                        $limit1 = 50;
                                        $limit = 50;
                                        $total_pages = $commonFunctions->getData('invty_pdt_details','');
                                        $total_pages = count($total_pages);
                                        $stages = 1;
                                        $page = @$_GET['page'];
                                        if($page){
                                            $start = ($page - 1) * $limit; 
                                        }else{
                                            $start = 0; 
                                        } 
                                        $search_con = "";
                                        if(!empty($_GET['search'])){
                                            $search_con = " AND reference_number LIKE '%".$_GET['search']."%' OR label LIKE '%".$_GET['search']."%' OR barcode_value LIKE '%".$_GET['search']."%' OR description LIKE '%".$_GET['search']."%' OR public_url LIKE '%".$_GET['search']."%' OR virtual_stock LIKE '%".$_GET['search']."%' OR physical_stock LIKE '%".$_GET['search']."%' OR price LIKE '%".$_GET['search']."%' ";
                                            $countryArr = $commonFunctions->getIDs('sys_erp_adm_countries','rowid'," WHERE label LIKE '%".$_GET['search']."%' ");
                                            if(!empty($country_ids)){ $search_con .= "  OR country_id IN(".$country_ids.") "; }
                                        }
                                        $where = " WHERE id ".$search_con." ORDER BY id DESC LIMIT $start, $limit ";
                                        // Initial page num setup
                                        if ($page == 0){ $page = 1; }
                                        $prev = $page - 1;  
                                        $next = $page + 1;  
                                        $lastpage = ceil($total_pages/$limit);  
                                        $LastPagem1 = $lastpage - 1;    
                                        $paginate = '';
                                        if($lastpage > 1)
                                        {       
                                            $paginate .= "<div class='paginate'>";
                                            // Previous

                                            if ($page > 1){
                                                $paginate.= "<a href='$targetpage&page=$prev'>Previous</a>";
                                            }else{
                                                $paginate.= "<span class='disabled'>Previous</span>";   }
                                            // Pages    
                                            if ($lastpage < 2 + ($stages * 2))  // Not enough pages to breaking it up
                                            {   
                                                for ($counter = 1; $counter <= $lastpage; $counter++)
                                                {
                                                    if ($counter == $page){
                                                        $paginate.= "<span class='current'>$counter</span>";
                                                    }else{
                                                        $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                }
                                            }
                                            elseif($lastpage > 2 + ($stages * 2))   // Enough pages to hide a few?
                                            {
                                                // Beginning only hide later pages
                                                if($page < 1 + ($stages * 2))   
                                                {
                                                    for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                    }
                                                    $paginate.= "...";
                                                    $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                    $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                                }
                                                // Middle hide some front and some back
                                                elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
                                                {
                                                    $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                    $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                    $paginate.= "...";
                                                    for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                    }
                                                    $paginate.= "...";
                                                    $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                    $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                                }
                                                // End only hide early pages
                                                else
                                                {
                                                    $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                    $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                    $paginate.= "...";
                                                    for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                                                    {
                                                        if ($counter == $page){
                                                            $paginate.= "<span class='current'>$counter</span>";
                                                        }else{
                                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}
                                                    }
                                                }       
                                            }       
                                                    // Next
                                            if ($page < $counter - 1){ 
                                                $paginate.= "<a href='$targetpage&page=$next'>Next</a>";
                                            }else{
                                                $paginate.= "<span class='disabled'>Next</span>";
                                                }
                                            $paginate.= "</div>";   
                                        }
                                        $productData = $commonFunctions->getData('invty_pdt_details',$where);

                                        $startP = $limit + $start;
                                        if($startP > @count($productData) ){
                                            $startP = @count($productData) + $start;
                                        }
                                        $productData1 = $commonFunctions->getData('invty_pdt_details','');
                                        echo "<span style='padding: 2px 5px 2px 5px;margin: 2px;border: 1px solid #999;text-decoration: none;color: #666;font-size: 15px;'>Listing ".$start." - ".$startP."</span>";
                                        echo "<span style='padding: 2px 5px 2px 5px;margin: 2px;border: 1px solid #999;text-decoration: none;color: #666;font-size: 15px;'>Total Products Listed ".@count($productData1)."</span>";
                                        echo "<div style='float: right;'>".$paginate."</div>";?>
                                        <table style="width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <!-- <th class="text-center">Product Type</th> -->
                                                    <th class="text-center">Label / Product Name</th>
                                                    <th class="text-center">Product Ref#</th>
                                                    <th class="text-center">Barcode Value</th>
                                                    <th class="text-center">Selling Price</th>
                                                    <th class="text-center">Physical Stock</th>
                                                    <th class="text-center">Virtual Stock</th>
                                                    <th class="text-center">Product Description</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                foreach ($productData as $row) { 
                                                ?>
                                                    <tr onclick="redirect_('product-card.php?product_id=<?php echo $row['id'];?>')">
                                                        
                                                        <th class="text-center"><?php echo $row['label'];?></th>
                                                        <th class="text-center"><?php echo $row['reference_number'];?></th>
                                                        <th class="text-center"><?php echo $row['barcode_value'];?></th>
                                                        <th class="text-center"><?php echo $row['price'];?></th>
                                                        
                                                        <th class="text-center">
                                                            <?php $physical_stock = $commonFunctions->getname($row['id'],"invty_pdt_stock_mgt","SUM(`stock_count`)","product_id"); 

                                                        echo !empty($physical_stock)?$physical_stock:0;
                                                        //$row['physical_stock'];?></th>
                                                        <th class="text-center"><?php echo !empty($row['virtual_stock'])?$row['virtual_stock']:0;?></th>

                                                        <th class="text-center" >
                                                            <div class="tooltip1"><div class="discription_cl"><?php echo $row['description'];?></div>
                                                                <span class="tooltiptext"><?php echo $row['description'];?></span>
                                                            </div>
                                                        </th>
                                                        
                                                        <!-- <th class="text-center">
                                                            <a class="btn btn-primary" href="product.php?state=edit&product_id=<?php echo $row['id'];?>"><i class="fa fa-pen"></i></a>
                                                        </th> -->
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    <!--/div>
                                </div-->
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->


<?php require "../../inc/footer.php"; ?>
<script type="text/javascript">
    $("#expand").click(function(){
        var accordioninput = $("#accordioninput").val();
        if(accordioninput == 0){
            //$(".accordion-class").html("<i class='dripicons-arrow-thin-down'></i>");
            $("#accordioninput").val(1);
        }else{
            //$(".accordion-class").html("<i class='dripicons-arrow-thin-right'></i>");
            $("#accordioninput").val(0);
        }
    })
    function redirect_(uri){
        window.location.href = uri;
    }
    $("#clearbtn").click(function(){
        $("#search").val('');
        $("#searchForm").submit();
    });
    /*$("#searchbtn").click(function(){
        currLoc = $(location).attr('href');
        window.location.href = currLoc+"&search="+$("#search").val();
    });
    $("#clearbtn").click(function(){
        currLoc = $(location).attr('href');
        window.location.href = currLoc;
    });*/
    $(document).ready(function() {       
        $('#product_image').bind('change', function() {
            var a=(this.files[0].size);
            if(a > 524288) {
                $("#product_image").val('');
                Swal.fire(
                    'Warning',
                    'Please make sure file size should not be more than 512kb!',
                    'error'
                )
                //alert('Please make sure file size should not be more than 512kb!');
            };
            var ext=(this.files[0].type);
            if($.inArray(ext, ['image/png','image/jpg','image/jpeg']) == -1) {
                Swal.fire(
                    'Warning',
                    'Only .png, .jpg and .jpeg format is allowed.',
                    'error'
                )
            }
        });
    });
    $(".save_form").click(function(){
        var label = $("#label").val();
        var reference_number = $("#reference_number").val();
        if(label != '' && reference_number != ''){
            $("#product_form").submit();
        }else{
            Swal.fire(
                'Error',
                'Please fill all required fields!',
                'error'
            )
        }
    });
    $(".clear_form").click(function(){
        $("#product_form").trigger("reset");
    });
</script>