<?php 
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');
$filepath = realpath(dirname(__FILE__));
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call"){
    require "../../inc/ajax_header.php";
    $country_id = $_POST["country_id"];
    $getData = $commonFunctions->getData('sys_erp_adm_countries_states'," WHERE country_id = '".$country_id."' and active = 1 ");
    $html = "";
    foreach ($getData as $rw) {
        $html .= "<option value='".$rw['rowid']."'>".$rw['label']."</option>";
    }
    echo json_encode(array("option"=>$html));
    exit();
}
if(!empty($_GET["action"]) and $_GET["action"] == "ajax_call1"){
    require "../../inc/ajax_header.php";
    $country_id = $_GET["country_id"];
    $state_id = $_GET["state_id"];
    $keyword = $_GET["keyword"]; 
    $getData = $commonFunctions->getData('sys_erp_adm_countries_states_cities'," WHERE country_id = '".$country_id."' and state_id = '".$state_id."' and name LIKE '%".$keyword."%' ");
    $html = "";
    $skillData = array(); 
    foreach ($getData as $rw) {
        $data['id'] = $rw['name']; 
        $data['value'] = $rw['name']; 
        array_push($skillData, $data); 
    } 
    echo json_encode($skillData);
    exit();
}
require "../../inc/header.php";
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_wrhus', "");
    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 = 'warehouse.php?state=list';</script>";
}
$msg = Session::get('msg');
Session::set("msg", NULL);
?>
    <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 Warehouse":"Warehouse 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);">Warehouses </a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo ($_GET['state'] != "list")?"Add Warehouse":"Warehouse List"; ?></a></li>
                        </ol>

                    </div><!--end col-->
                    <div class="col-auto align-self-center">
                        <a href="warehouse.php?state=<?php echo $_GET['state'];?>&action=export" class="btn btn-sm btn-outline-primary">
                            <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-download align-self-center icon-xs"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg> Download Warehouse List
                        </a>
                        <a href="import-warehouse.php" class="btn btn-sm btn-outline-dark">
                            <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-upload align-self-center icon-xs"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg> Import Warehouse List
                        </a>
                    </div>
                    <!-- <div class="col-auto align-self-center">
                        <a href="#" class="btn btn-sm btn-outline-primary" id="Dash_Date">
                            <span class="day-name" id="Day_Name">Today:</span>&nbsp;
                            <span class="" id="Select_date">Jan 11</span>
                            <i data-feather="calendar" class="align-self-center icon-xs ml-1"></i>
                        </a>
                        <a href="#" 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">
                                <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                                    <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>
                                <?php endif; ?>
                            </div>

                            <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] != "list")): ?>
                                <div class="form-group col-md-6" style="text-align: right;">
                                    <a class="btn btn-outline-dark" href="warehouse.php?state=list" role="button"> Back to Warehouses List</a>
                                </div>
                            <?php endif; ?>

                            <?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                            <div class="form-group searchForm col-md-6">
                                <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>
                            </div>
                            <?php endif; ?>
                        </div>
                    </h4>
                    <?php echo !empty($msg)?$msg:''; ?>        
                </div>
       
                <div class="card-body">
                    <div class="row">
                        <?php if(@$_GET['state'] != "list"): ?>
                            <?php 
                                if(@$_GET['warehouse_id'] != ''){
                                    $editData = $commonFunctions->getRowData('invty_wrhus'," WHERE id = '".$_GET['warehouse_id']."' ");
                                }
                                if(!empty($_POST)){
                                    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>');
                                    }
                                    if(!empty($_POST['reference_number'])){
                                        $added_by = $_SESSION['id'];
                                        if(empty($_POST['warehouse_id'])){
                                            $commonFunctions->addData('invty_wrhus'," (reference_number,short_name_location,parent_id,description,address,zip_code,city,country_id,province) VALUES ('".$_POST['reference_number']."','".$_POST['short_name_location']."','".$_POST['parent_id']."','".$_POST['description']."','".$_POST['address']."','".$_POST['zip_code']."','".$_POST['city']."','".$_POST['country_id']."','".$_POST['state_id']."' ) ",'warehouse.php?state=list');
                                        }else{
                                            $updated_by = $_SESSION['id'];
                                            $commonFunctions->updateData('invty_wrhus'," WHERE id = '".$_POST['warehouse_id']."' ", " reference_number='".$_POST['reference_number']."', short_name_location='".$_POST['short_name_location']."' , parent_id='".$_POST['parent_id']."' , description='".$_POST['description']."' , address='".$_POST['address']."' , zip_code='".$_POST['zip_code']."' , city='".$_POST['city']."', country_id='".$_POST['country_id']."', province='".$_POST['state_id']."' ",'warehouse.php?state=list');
                                        }
                                    }
                                }
                            ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card">
                                    <div class="card-body"-->
                                        <form action="" method="post">
                                            <input type="hidden" name="warehouse_id" value="<?php echo @$_GET['warehouse_id'];?>">

                                            <div class="form-row">
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="reference_number" class="">Reference Number</label>
                                                    <input name="reference_number" id="reference_number" placeholder="Please enter reference number" type="text" class="form-control" value="<?php echo @$editData['reference_number'];?>">
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="short_name_location" class="">Short Name Location</label>
                                                    <textarea name="short_name_location" class="form-control" placeholder="Short Name Location"><?php echo @$editData['short_name_location'];?></textarea>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="description" class="">Description</label>
                                                    <textarea name="description" class="form-control" placeholder="Description"><?php echo @$editData['description'];?></textarea>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="address" class="">Address</label>
                                                    <textarea name="address" class="form-control" placeholder="Address"><?php echo @$editData['address'];?></textarea>
                                                </div>
                                                <div class="col-md-6 position-relative form-group">
                                                    <label for="zip_code" class="">Zipcode</label>
                                                    <input name="zip_code" id="zip_code" placeholder="Please enter Zipcode" type="text" class="form-control" value="<?php echo @$editData['zip_code'];?>">
                                                </div>
                                                <div class="position-relative form-group col-md-6">
                                                    <label for="parent_id" class="">Add In</label>
                                                    <?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
                                                    <select name="parent_id" id="parent_id" class="select2 form-control" >
                                                        <option value="0">Select</option>
                                                        <?php foreach ($warehouseData as $rw) { ?>
                                                            <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['parent_id'] == $rw['id'])?"selected":"";?> ><?php echo $rw['short_name_location']; ?></option>     
                                                        <?php } ?>
                                                    </select>
                                                </div>

                                                <div class="position-relative form-group col-md-4">
                                                    <label for="country_id" class=""> Country</label>
                                                    <?php $countryData = $commonFunctions->getData('sys_erp_adm_countries',' WHERE active = 1 '); ?>
                                                    <select name="country_id" id="country" 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="state_id" class=""> State / Province </label>
                                                    <?php $stateData = $commonFunctions->getData('sys_erp_adm_countries_states',' WHERE active = 1 '); ?>
                                                    <select name="state_id" id="state" class="select2 form-control" >
                                                        <option value="0">Select State / Province</option>
                                                        <?php foreach ($stateData as $rw) { ?>
                                                            <option value="<?php echo $rw['rowid'];?>"  <?php echo (@$editData['state_id'] == $rw['rowid'])?"selected":"";?> ><?php echo $rw['label']."(".$rw['region_code'].")"; ?></option>     
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-4 position-relative form-group">
                                                    <label for="city" class="">City</label>
                                                    <input name="city" id="city" placeholder="Please enter city" type="text" class="form-control" value="<?php echo @$editData['city'];?>">
                                                </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: 
                            if(!empty($_GET['warehouse_id'])){
                                $commonFunctions->updateData('invty_wrhus'," WHERE id = '".$_GET['warehouse_id']."' ", " status ='".$_GET['flag']."'",'warehouse.php?state=list'); 
                            }
                            ?>
                            <div class="col-md-12">
                                <!--div class="main-card mb-3 card"-->
                                    <style type="text/css">
                                        tr {cursor: pointer;}
                                    </style>
                                    <!--div class="card-body"-->
                                        <table style="width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <th class="text-center">Warehouse Reference No.</th>
                                                    <th class="text-center">Warehouse Name</th>
                                                    <th class="text-center">Address</th>
                                                    <th class="text-center">City</th>
                                                    <th class="text-center">Country</th>
                                                    <th class="text-center">Status</th>
                                                    
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $targetpage = "warehouse.php?state=list";

                                                $limit = 50;
                                                $total_pages = $commonFunctions->getData('invty_wrhus','');
                                                $total_pages = count($total_pages);
                                                $stages = 3;
                                                $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 short_name_location LIKE '%".$_GET['search']."%' OR description LIKE '%".$_GET['search']."%' OR address LIKE '%".$_GET['search']."%' OR zip_code LIKE '%".$_GET['search']."%' OR city 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 < 7 + ($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 > 5 + ($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_wrhus',$where);
                                                $i=1;
                                                foreach ($productData as $row) { 
                                                    $i++;
                                                ?>
                                                    <tr>
                                                        <th class="text-primary" onclick="redirect_('warehouse.php?state=edit&warehouse_id=<?php echo $row['id'];?>')" ><?php echo $row['reference_number'];?></th>
                                                        <th class="text-primary" onclick="redirect_('warehouse.php?state=edit&warehouse_id=<?php echo $row['id'];?>')" ><?php echo $row['short_name_location'];?></th>
                                                        <th class="text-center"><?php echo $row['address'];?></th>
                                                        
                                                        <th class="text-center"><?php echo $row['city'];?></th>
                                                        <th class="text-center"><?php echo $commonFunctions->getname($row['country_id'],"sys_erp_adm_countries","label","rowid");?>(<?php echo $commonFunctions->getname($row['country_id'],"sys_erp_adm_countries","code","rowid");?>)</th>
                                                        <th>
                                                            <?php
                                                                $flag = '';
                                                                $flag_state = 0;
                                                                if($row['status'] == 0){
                                                                    $flag = 'checked';
                                                                    $flag_state = 1;
                                                                }
                                                                $url = 'warehouse.php?state=list&warehouse_id='.$row['id'].'&flag='.$flag_state;
                                                                echo '<div class="custom-control custom-switch switch-primary">
                                                                    <input type="checkbox" class="custom-control-input" id="customSwitchPrimary'.$i.'" '.$flag.' onchange=change_flag("'.$url.'")>
                                                                    <label class="custom-control-label" for="customSwitchPrimary'.$i.'"></label>
                                                                </div>';
                                                            ?>
                                                        </th>
                                                        <!-- <th class="text-center">
                                                            <a class="btn btn-primary" href="warehouse.php?state=edit&warehouse_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">
function change_flag(url){
    window.location.href = url;
}
function redirect_(uri){
    window.location.href = uri;
}
$("#clearbtn").click(function(){
    $("#search").val('');
    $("#searchForm").submit();
});
$("#country").change(function(){
    var country = $("#country option:selected").val();
    $.ajax({
        type: 'POST',
        url: "",
        data: {"country_id":country,"action":"ajax_call"},
        success: function(response) { 
            obj = JSON.parse(response);
            $("#state").html("<option value=''>Select State / Province</option>"+obj.option);
        }
    });
})
$(function() {
    $("#city").autocomplete({
        source: function(request, response) {
            $.getJSON("", { country_id: $('#country option:selected').val(),state_id: $('#state option:selected').val(),keyword: request.term,action:"ajax_call1" }, response);
        },
        minLength: 2,
    });
});
</script>