<?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>";
}
?>
<?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,selling_price_type,min_selling_price_type,buying_price_type,cost_price_type ".$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']."','".@$_POST['selling_price_type']."','".@$_POST['min_selling_price_type']."','".@$_POST['buying_price_type']."','".@$_POST['cost_price_type']."'".$fileName.") ",'product.php?state=list');
            }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']."', selling_price_type='".@$_POST['selling_price_type']."', min_selling_price_type='".@$_POST['min_selling_price_type']."', buying_price_type='".@$_POST['buying_price_type']."', cost_price_type='".@$_POST['cost_price_type']."', updated_by='".$updated_by."'".$fileName,'product.php?state=list');
            }
        }
    }
    ?>
    <!-- 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 active"><?php echo ($_GET['state'] != "list")?"Add Products":"Product List"; ?></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-success save_form"><i class="fas fa-save align-self-center icon-xs"></i> Save</button>
                            <button type="button" class="btn btn-sm btn-danger clear_form"><i class="fas fa-times-circle align-self-center icon-xs"></i> Clear</button>
                            <a href="product.php?state=list"><button type="button" class="btn btn-sm btn-secondary clear_form"><i class="fas fa-angle-double-left align-self-center icon-xs"></i> 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 -->
<?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>    
    
    <?php $productData1 = $commonFunctions->getData('invty_pdt_details',''); ?>
    <div class="row">
        <div class="col-lg-12">
            <div class="row justify-content-center">
                <div class="col-md-6 col-lg-3">
                    <div class="card report-card">
                        <div class="card-body">
                            <div class="row d-flex justify-content-center">
                                <div class="col">
                                    <p class="text-dark mb-0 font-weight-semibold">Total Inventory</p>
                                    <h3 class="m-0">0</h3>
                                    <p class="mb-0 text-truncate text-muted">In Inventory</p>
                                </div>
                                <div class="col-auto align-self-center">
                                    <div class="report-main-icon bg-light-alt">
                                        <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-users align-self-center text-muted icon-sm"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>  
                                    </div>
                                </div>
                            </div>
                        </div><!--end card-body--> 
                    </div><!--end card--> 
                </div> <!--end col--> 
                <div class="col-md-6 col-lg-3">
                    <div class="card report-card">
                        <div class="card-body">
                            <div class="row d-flex justify-content-center">                                                
                                <div class="col">
                                    <p class="text-dark mb-0 font-weight-semibold">Inventory in</p>
                                    <h3 class="m-0">0</h3>
                                    <p class="mb-0 text-truncate text-muted">Barwa Shop 4</p>
                                </div>
                                <div class="col-auto align-self-center">
                                    <div class="report-main-icon bg-light-alt">
                                        <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-clock align-self-center text-muted icon-sm"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>  
                                    </div>
                                </div> 
                            </div>
                        </div><!--end card-body--> 
                    </div><!--end card--> 
                </div> <!--end col--> 
                <div class="col-md-6 col-lg-3">
                    <div class="card report-card">
                        <div class="card-body">
                            <div class="row d-flex justify-content-center">                                                
                                <div class="col">
                                    <p class="text-dark mb-0 font-weight-semibold">Total Products</p>
                                    <h3 class="m-0"><?php echo @count($productData1); ?></h3>
                                    <p class="mb-0 text-truncate text-muted">Listed Products</p>
                                </div>
                                <div class="col-auto align-self-center">
                                    <div class="report-main-icon bg-light-alt">
                                        <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-clock align-self-center text-muted icon-sm"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>  
                                    </div>
                                </div> 
                            </div>
                        </div><!--end card-body--> 
                    </div><!--end card--> 
                </div> <!--end col--> 
                <div class="col-md-6 col-lg-3">
                     
                </div> <!--end col-->                        
            </div><!--end row-->
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <?php echo !empty($msg)?$msg:''; ?>
            <div class="card">
                <div class="card-header">
                    <div class="row align-items-center">
                        <div class="col">                      
                            <a href="product.php?state=add"><button type="button" class="btn btn-outline-primary">Add Product</button></a>                     
                        </div><!--end col--> 
                        <div class="col">                      
                            <form action="" id="searchForm" method="GET">
                                <div class="input-group">
                                    <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
                                    <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>"> 

                                    <input type="text" class="form-control" name="search" id="search" placeholder="Search" aria-label="Recipient's username" aria-describedby="basic-addon2" value="<?php echo @$_GET['search']; ?>">

                                    <button class="btn btn-soft-secondary" type="submit" id="searchbtn button-addon2"><i class="fas fa-search"></i></button>
                                </div>
                            </form>
                        </div><!--end col-->                                        
                    </div>  <!--end row-->                                  
                </div><!--end card-header-->
                <div class="card-body">
                    <div class="table-responsive1 browser_users">
                        <?php 
                        $targetpage = "product.php?state=list";
                        $limit1 = 10;
                        $limit = 10;
                        $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','');

                        $Listing = "<ul class='pagination'><li class='page-item'><a class='page-link' href='javascript:void(0);'>Listing</a></li> <li class='page-item'> <a class='page-link' href='javascript:void(0);'>$start - $startP</a> </li> </ul>";

                        //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>"; ?>

                        <table class="table table-hover mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th class="border-top-0">Label / Product Name</th>
                                    <th class="border-top-0">Product Ref#</th>
                                    <th class="border-top-0">PN# / Barcode</th>
                                    <th class="border-top-0">Selling Price</th>
                                    <th class="border-top-0">Physical Stock</th>                                                    
                                    <th class="border-top-0">Ordered</th>
                                    <th class="border-top-0">Product Description</th>
                                </tr><!--end tr-->
                            </thead>
                            <tbody>
                                <?php foreach ($productData as $row) {  ?>
                                    <tr>                                             
                                        <td onclick="redirect_('product-card.php?product_id=<?php echo $row['id'];?>')" ><a href="javascript:void(0);" class="text-primary"><?php echo $row['label'];?></a></td>
                                        <td onclick="redirect_('product-card.php?product_id=<?php echo $row['id'];?>')"><a href="javascript:void(0);" class="text-primary"><?php echo $row['reference_number'];?></a></td>
                                        <td><?php echo $row['barcode_value'];?></td>
                                        <td><?php echo $row['price']." /- QAR";?></td>
                                        <td>
                                            <?php $physical_stock = $commonFunctions->getname($row['id'],"invty_pdt_stock_mgt","SUM(`stock_count`)","product_id"); 

                                            $physical_stock = !empty($physical_stock)?$physical_stock:0;
                                            if($physical_stock==0){ ?>
                                                <span class="badge badge-soft-danger"><?php echo $physical_stock;?></span>
                                            <?php }else{ ?>
                                                <span class="badge badge-soft-success"><?php echo $physical_stock;?></span>
                                            <?php } ?>
                                        </td>
                                        <td>
                                            <span class="badge badge-soft-secondary"><?php echo !empty($row['virtual_stock'])?$row['virtual_stock']:0;?></span>
                                        </td> 
                                        <td class="text-center" >
                                            <div class="discription_cl">
                                                <div class="tooltip1">
                                                    <div class="discription_cl"><?php echo $row['description'];?></div>
                                                    <span class="tooltiptext"><?php echo $row['description'];?></span>
                                                </div>
                                            </div>
                                        </td>
                                    </tr><!--end tr-->  
                                <?php } ?>   
                            </tbody>
                        </table> <!--end table-->                                               
                        <br>
                    </div><!--end /div-->
                </div><!--end card-body--> 
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="page-title-box pt-0">
                        <div class="row">
                            <div class="col">
                                 <?php echo $Listing;?>
                            </div><!--end col-->
                            <div class="col-auto align-self-center">
                                <?php echo "<div style='float: right;'>".$paginate."</div>";?>
                            </div><!--end col-->  
                        </div><!--end row-->                                                              
                    </div><!--end page-title-box-->
                </div><!--end col-->
            </div>
                
        </div> <!-- end col -->
    </div> <!-- end row -->
<?php else: ?>
    <div class="row">
        <div class="col-12">
            <?php echo !empty($msg)?$msg:''; ?>
            <div class="tab-content" id="pills-tabContent">

                <!-- User Profile - Start --->
                <div class="tab-pane fade show active" role="tabpanel" aria-labelledby="settings_detail_tab">
                    <form id="product_form" action="" method="post" enctype="multipart/form-data">
                        <div class="row">
                            <input type="hidden" name="product_id" value="<?php echo ($_GET['state'] == 'edit')?@$_GET['product_id']:0;?>">

                            <input type="hidden" name="product_type" value="1">
                            <!-- Personal Information Card - Start --->
                            <div class="col-lg-6 col-xl-6">
                                <div class="card">
                                    <div class="card-header">
                                        <div class="row align-items-center">
                                            <div class="col-11">                      
                                                <h4 class="card-title text-left">Product Details <label class="col-xl-3 col-lg-3 mb-lg-0 align-self-center">( Basic )</label></h4>                      
                                            </div><!--end col-->                                                 
                                        </div>  <!--end row-->                                  
                                    </div><!--end card-header-->
                                    <div class="card-body">                                                                          
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Label / Product Name <span class="error">*</span></label>
                                            <div class="col-lg-9 col-xl-8">
                                                <input name="label" id="label" placeholder="Please enter label" type="text" class="form-control" value="<?php echo @$editData['label'];?>" required="">
                                            </div>
                                        </div>
                                         
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Description</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <textarea name="description" class="form-control"><?php echo @$editData['description'];?></textarea>
                                            </div>
                                        </div>                                    
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Product Image</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <input type="file" name="product_images" class="custom-file-input" id="product_image">
                                                 
                                                <label class="custom-file-label" for="product_image">Choose file</label>
                                            </div>
                                        </div>  
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Nature of Product</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <select class="form-control" name="nature" id="nature">
                                                    <option value="1" <?php echo (@$editData['nature'] == "1")?"selected":"";?> >Manufactured Product</option>
                                                    <option value="0" <?php echo (@$editData['nature'] == "0")?"selected":"";?> >Raw Material</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Country of Origin</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <?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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Public URL</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                    </div>                                            
                                </div>

                                <div class="card">
                                    <div class="card-header">
                                        <div class="row align-items-center">
                                            <div class="col-11">                      
                                                <h4 class="card-title text-left">Stock &amp; Inventory </h4>                      
                                            </div><!--end col-->                                                   
                                        </div>  <!--end row-->                                  
                                    </div><!--end card-header-->
                                    <div class="card-body">                                                                          
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Default Warehouse</label>
                                            <div class="col-lg-9 col-xl-8">
                                               <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                                                <select class="form-control" name="default_warehouse_id" id="default_warehouse_id">
                                                    <option value="0">Select Warehouse</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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center"> Stock Limit for Alert</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                        <!-- <div class="form-group row">                    
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Desired Optimal Stock</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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> -->    
                                        <div class="form-group row">             
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Desired Optimal Stock</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>    
                                        <!-- <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Virtual Stock</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Physical Stock</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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><!--end card-body-->
                                </div><!--end card-->

                            </div> <!--end col--> 
                            <!-- Contact Information Personal  Card - End --->

                            <!-- Contact Information Card Official - Start --->
                            <div class="col-lg-6 col-xl-6">

                                <div class="card">
                                    <div class="card-header">
                                        <div class="row align-items-center">
                                            <div class="col-12">                      
                                                <h4 class="card-title text-left">Barcode / Ref Details <label class="col-xl-8 col-lg-8 mb-lg-0 align-self-center">( Barcode Value helps in tracking the Product )</label></h4>
                                            </div><!--end col-->                                                      
                                        </div>  <!--end row-->                                  
                                    </div><!--end card-header-->
                                    <div class="card-body">   
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center"> Reference ID / Number</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>                                                                       
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Barcode Type</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <select class="form-control" name="barcode_type" id="barcode_type">
                                                    <option value="">Select Barcode Type</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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Barcode Value</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                    </div><!--end card-body-->
                                </div><!--end card-->

                                <div class="card">
                                    <div class="card-header">
                                        <div class="row align-items-center">
                                            <div class="col-11">                      
                                                <h4 class="card-title text-left">Sales &amp; Purchase</h4>
                                            </div><!--end col-->                                                      
                                        </div>  <!--end row-->                                  
                                    </div><!--end card-header-->
                                    <div class="card-body">                                                                          
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Sales Status</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Purchase Status</label>
                                            <div class="col-lg-9 col-xl-8">
                                                <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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Selling Price</label>
                                            <div class="col-lg-9 col-xl-4">
                                               <input name="price" id="price" placeholder="Please enter price" type="text" class="form-control" value="<?php echo (empty(@$editData['price']))?0:@$editData['price'];?>" >
                                            </div>
                                            <div class="col-lg-9 col-xl-4">
                                                <select class="form-control" name="selling_price_type" id="selling_price_type" >
                                                    <option value="">Select</option>
                                                    <option value="Net of TAX" <?php echo (@$editData['selling_price_type'] == "Net of TAX")?"selected":"";?> >Net of TAX</option>
                                                    <option value="Inc. TAX" <?php echo (@$editData['selling_price_type'] == "Inc. TAX")?"selected":"";?> >Inc. TAX</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Min. Selling Price</label>
                                            <div class="col-lg-9 col-xl-4">
                                               <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="col-lg-9 col-xl-4">
                                                <select class="form-control" name="min_selling_price_type" id="min_selling_price_type" >
                                                    <option value="">Select</option>
                                                    <option value="Net of TAX" <?php echo (@$editData['min_selling_price_type'] == "Net of TAX")?"selected":"";?> >Net of TAX</option>
                                                    <option value="Inc. TAX" <?php echo (@$editData['min_selling_price_type'] == "Inc. TAX")?"selected":"";?> >Inc. TAX</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Buying Price</label>
                                            <div class="col-lg-9 col-xl-4">
                                               <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-lg-9 col-xl-4">
                                               <select class="form-control" name="buying_price_type" id="buying_price_type" >
                                                    <option value="">Select</option>
                                                    <option value="Net of TAX" <?php echo (@$editData['buying_price_type'] == "Net of TAX")?"selected":"";?> >Net of TAX</option>
                                                    <option value="Inc. TAX" <?php echo (@$editData['buying_price_type'] == "Inc. TAX")?"selected":"";?> >Inc. TAX</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Cost Price</label>
                                            <div class="col-lg-9 col-xl-4">
                                               <input name="cost_price" id="cost_price" placeholder="Please enter cost price" type="text" class="form-control" value="<?php echo (empty(@$editData['cost_price']))?0:@$editData['cost_price'];?>" >
                                            </div>
                                            <div class="col-lg-9 col-xl-4">
                                               <select class="form-control" name="cost_price_type" id="cost_price_type" >
                                                    <option value="">Select</option>
                                                    <option value="Net of TAX" <?php echo (@$editData['cost_price_type'] == "Net of TAX")?"selected":"";?> >Net of TAX</option>
                                                    <option value="Inc. TAX" <?php echo (@$editData['cost_price_type'] == "Inc. TAX")?"selected":"";?> >Inc. TAX</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Selling Type</label>
                                            <div class="col-lg-9 col-xl-8">
                                               <select class="form-control" name="selling_type" id="selling_type">
                                                    <option value="">Select</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>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center">Accounting Code (Sale)</label>
                                            <div class="col-lg-9 col-xl-8">
                                               <input type="text" id="accountancy_code_sell" name="accountancy_code_sell" class="flat accountancy_code_sell form-control" value="">
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center"> Accounting Code (Purchase)</label>
                                            <div class="col-lg-9 col-xl-8">
                                               <input type="text" id="accountancy_code_purchase" name="accountancy_code_purchase" class="flat accountancy_code_purchase form-control" value="">
                                            </div>
                                        </div>
                                        <div class="form-group row">                                         
                                            <label class="col-xl-3 col-lg-3 text-left mb-lg-0 align-self-center"> Product Tags / Categories </label>
                                            <div class="col-lg-9 col-xl-8">
                                                <?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>
                                    </div><!--end card-body-->
                                </div><!--end card-->
                                
                            </div> <!-- end col -->
                            <!-- Contact Information Official Card - End --->
                        </div><!--end row-->
                    </form>                                       
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?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>