<?php 
session_start();
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('memory_limit', '5G');
error_reporting(E_ALL); 
include_once './header.php';
?>

 <div class="container">
        <h1>Import Category </h1> 
<form action="" method="POST" enctype="multipart/form-data" >
    <div class="form-group">
    <label for="assign_category">Select Category Add or update:</label>
    <select name="assign_category" class="form-control" required >
        <option value="">Select Category</option>
        <option value="1">Only current uploaded category</option>
        <option value="2">Assign more category</option>
        <option value="3">Remove Category From sku</option>
    </select>
  </div>
  <div class="form-group">
    <label for="csvfile">Select CSV file:</label>
    <input type="file" name="csvfile" id="csvfile" class="form-control-file" required>
  </div>
  <button type="submit" class="btn btn-primary">Upload</button>
</form>

<?php

if (isset($_FILES['csvfile']) && $_FILES['csvfile']['error'] == UPLOAD_ERR_OK && $_FILES['csvfile']['type'] == 'text/csv') {
  $csvfile = $_FILES['csvfile']['tmp_name'];
  $target_dir = "/home/webdevel/public_html/ah-admin/import-category/"; // directory path for file uploads
$target_file = $target_dir . basename($_FILES["csvfile"]["name"]);
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
include_once './config.php';
    $database = new Database();
    $db = $database->getConnection();
?><div class="loader" id="alrt"></div>
<?php
    $arrResult = array();
    $headers = false;
    $handle = fopen($csvfile, "r");
    if (empty($handle) === false) {
        $i=0;
        while (($data = fgetcsv($handle, 10000000, ",")) !== FALSE) {
          
            if (!$headers) {
                $headers[] = $data;
              
            } else {
                     // // Load product ID
                    $getProductId= "SELECT entity_id FROM ahqa_catalog_product_entity WHERE sku='".$data[0]."' ";
                    $stmt = $db->prepare($getProductId);
                    $stmt->execute();
                    $itemCount1 = $stmt->rowCount();
                    $result=[];
                    if($itemCount1>0){
                          $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    }
                    if($_POST['assign_category']=='1' && $itemCount1>0){ //DELETE OTHER CATEGORY FROM PRODUCT
                        $sqlQueryDelete = "DELETE FROM ahqa_catalog_category_product
                            WHERE product_id=".$result['entity_id']."";
                        $stmtDel = $db->prepare($sqlQueryDelete);
                        $stmtDel->execute();
                    }
                    $numcols = count($data);
                    for($j=1; $j<$numcols;$j++){
                        if($data[$j]!=''){
                             
                                try {
                                       // // Load Category ID
                                    $getCategoryId= "SELECT entity_id FROM ahqa_catalog_category_product WHERE value = '".$data[$j]."' ORDER BY value_id ASC LIMIT 1 ";
                               
                                    $stmt2 = $db->prepare($getCategoryId);
                                    $stmt2->execute();
                                    $itemCount2 = $stmt2->rowCount();
                                    
                                    if($itemCount1>0 && $itemCount2>0){
                                          $result2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                                          
                                           if($_POST['assign_category']=='3'){ //DELETE OTHER CATEGORY FROM PRODUCT
                                           
                                              echo $result['entity_id'];
                                                    
                                                    $sqlQueryDelete = "DELETE FROM ahqa_catalog_category_product WHERE product_id=".$result['entity_id']." AND category_id=".$result2['entity_id']." ";
                                                    $stmtDel = $db->prepare($sqlQueryDelete);
                                                    $stmtDel->execute();
                                          }else{
                                                  
                                        //$data[$j].' = '.$data[$j].'=='.$result2['entity_id'].'==p=='.$result['entity_id'].'<br>';
                                        
                                        $sqlQuery2 = "INSERT IGNORE INTO ahqa_catalog_category_product (category_id, product_id) VALUES (".$result2['entity_id'].", ".$result['entity_id'].")";
                                        $stmt3 = $db->prepare($sqlQuery2);
                                        if($stmt3->execute()){
                                          http_response_code(200);
                                        } else{
                                             http_response_code(404);
                                            echo $data[$j].' Sku is not updated with this = '.$data[$j].'<br>';
                                            
                                        }
                                    
                                     }
                                          
                                      
                
                                    }else{
                                         if($itemCount2==0){
                                              echo $data[0].'-->'.$data[$j].' This Category does not exist<br>';
                                         }else{
                                             echo $data[0].'-->'.$data[$j].' This sku does not exist<br>';
                                         }
                                    }
                                    
                                } catch (\Exception $e) {
                                    echo $er->getMessage() . "====>\n".$data[0].'<br>';
                                }
                
                        }
                    }
            }
        }
        fclose($handle);
    }
  move_uploaded_file($csvfile, $target_dir . $_FILES['csvfile']['name']);
  echo 'Category has been sucessfully imported';
?>
<script>
    window.setTimeout(function(){ document.getElementById('alrt').style.display = "none";},5000);
    
</script>

<?php
}//form submited
else {
  //echo "Error uploading CSV file";
}

?>
<style>
    .loader{
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') 
              50% 50% no-repeat rgb(249,249,249);
}
</style>
</div>
</body>
</html>