<?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/warehouse/Warehouse-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('Warehouse Details List');
    
    ob_start();
    $objPHPExcel->setActiveSheetIndex(0); // Create new worksheet
    $head = 0;
    $table_head = array("Reference Number#","Short Name Location","Description","Address","Zipcode","Country","State / Province","City");
    foreach($table_head as $value)
    {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($head, 2, $value);   
        $head++;
    }
    $firstRowData = "Warehouse 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['reference_number']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,$body,$row['short_name_location']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,$body,$row['description']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3,$body,$row['address']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4,$body,$row['zip_code']);
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5,$body,$commonFunctions->getname($row['country_id'],"sys_erp_adm_countries","label","rowid"));
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6,$body,$commonFunctions->getname($row['province'],"sys_erp_adm_countries_states","label","rowid"));
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7,$body,$row['city']);
        $body++;
    }
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    // If you want to output e.g. a PDF file, simply do:
    $objWriter->save('../../uploads/product-services/warehouse/Warehouse-Details-List.xls');
    echo "<script>window.open('../../uploads/product-services/warehouse/Warehouse-Details-List.xls');</script>";
    echo "<script>window.location.href = 'import-warehouse.php';</script>";
}
if(!empty($_POST['action']) and @$_POST['action'] == "import"){
    require '../../lib/Excel-Library/php-excel-reader/excel_reader2.php';
    require '../../lib/Excel-Library/SpreadsheetReader.php';
    
    if(isset($_FILES['excel_file']['name']) && $_FILES['excel_file']['name'] != "") {
        $allowedExtensions = array("xls","xlsx");
        $ext = pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION);
        if(in_array($ext, $allowedExtensions)) {
            $file_size = $_FILES['excel_file']['size'] / 1024;
            if($file_size < 2048) {
                $file = "../../uploads/product-services/warehouse/".$_FILES['excel_file']['name'];
                $isUploaded = copy($_FILES['excel_file']['tmp_name'], $file);
                if($isUploaded) {
                    include("../../lib/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php");
                    try {
                        //Load the excel(.xls/.xlsx) file
                        $objPHPExcel = PHPExcel_IOFactory::load($file);
                    } catch (Exception $e) {
                        die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
                    }

                    error_reporting(E_ALL);
                    ini_set('display_errors', TRUE);
                    ini_set('display_startup_errors', TRUE);

                    //An excel file may contains many sheets, so you have to specify which one you need to read or work with.
                    $sheet = $objPHPExcel->getSheet(0);
                    //It returns the highest number of rows
                    $total_rows = $sheet->getHighestRow();
                    //It returns the highest number of columns
                    $highest_column = $sheet->getHighestColumn();
                    $affected_rows = 0;
                    for($row =2; $row <= $total_rows; $row++) {
                        $single_row = $sheet->rangeToArray('A' . $row . ':' . $highest_column . $row, NULL, TRUE, FALSE);
                        
                        $reference_number = $single_row[0][0];
                        $short_name_location = $single_row[0][1];
                        $description = $single_row[0][2];
                        $address = $single_row[0][3];
                        $zip_code = $single_row[0][4];
                        $city = $single_row[0][7];
                        
                        $country_id = 0;
                        if(!empty($single_row[0][5])){
                            $country = $commonFunctions->getName($single_row[0][5],'sys_erp_adm_countries','rowid','label');
                            if(!empty($country)){
                                $country_id = $country;
                            }
                        }
                        $state_id = 0;
                        if(!empty($single_row[0][6])){
                            $state = $commonFunctions->getName($single_row[0][6],'sys_erp_adm_countries_states','rowid','label');
                            if(!empty($state)){
                                $state_id = $state;
                            }
                        }
                        

                        $commonFunctions->addImportData('invty_wrhus'," (reference_number,short_name_location,description,address,zip_code,city,province,description,public_url,default_warehouse_id,country_id) VALUES ('1','".$reference_number."','".$short_name_location."','".$description."','".$address."','".$zip_code."','".$city."','".$state_id."','".$description."','".$public_url."','".$default_warehouse_id."','".$country_id."' ) ",'');
                        $affected_rows = $affected_rows + 1;
                    }
                    Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
                        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                        <strong>Success !</strong> Wow, Your Information added Successfully !<br>Added Records - '.$affected_rows.'</div>');
                    @unlink($file);
                    echo "<script>window.location.href='';</script>";
                }else{
                    Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> File not uploaded!</div>');
                }
            }else{
                Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Maximum file size should not cross 2 MB on size!</div>');
            }
        }else{
            Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error !</strong> Please select valid format!</div>');
        }
    }    
}

?>

    <!-- 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 "Import Warehouse"; ?></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);">Warehouse</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo "Import Warehouse"; ?></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> -->

                        <!--a href="product.php?action=export" class="btn btn-sm btn-outline-primary">
                            <i data-feather="download" class="align-self-center icon-xs"></i>
                        </a-->
                    </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-outline-primary" href="warehouse.php?state=add" role="button"><i class="fas fa-plus mr-2"></i> Add New Warehouses</a>
                            </div> 
                            <div class="form-group searchForm col-md-6">
                                
                            </div>
                        </div>
                    </h4>
                </div>
       
                <div class="card-body">
                    <div class="form-row">
                        
                        <div class="col-md-8">
                            <form id="ImportForm" enctype="multipart/form-data" method="post">
                                <div class="form-row">
                                    <div class="col-md-12">
                                        <span><b>Note - </b></span>
                                        <br>
                                        <span>1. File format should be .xls file.</span>
                                        <br>
                                        <span>2. File not more than 2MB.</span>
                                        <br>
                                        <div id="errorMessage"><?php echo !empty($msg)?$msg:''; ?></div>
                                        <br>
                                        <br>
                                    </div>
                                    <div class="col-md-6">
                                        <input type="hidden" name="action" value="import">
                                        <input type="file" name="excel_file" id="inpFile" required="">
                                    </div>
                                    <div class="col-md-6">
                                        <button type="submit" class="btn btn-sm btn-outline-success">Import Excel Data</button>
                                        <button type="button" class="btn btn-sm btn-outline-primary">Sample Excel Format</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        
                        <div class="col-md-4"></div>
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->

<?php require "../../inc/footer.php"; ?>
<script type="text/javascript">
    function redirect_(uri){
        window.location.href = uri;
    }
    $("#clearbtn").click(function(){
        $("#search").val('');
        $("#searchForm").submit();
    });
</script>