<?php

session_start();
error_reporting(1);
ini_set('display_errors', 1);
require_once "../config.php";
/*include_once "../ichat/admin/route.php";
if ($session->is_logged_in() != true ) {
        redirect_to(WEB_LINK.'/login');
} else {
    $current_user = User::get_specific_id($session->admin_id);
    $current_user->set_online();
    $group = $current_user->prvlg_group;
}*/


/*if(!isset($_GET['start']))
{
    die("Page Not Found");
}

$start = $_GET['start'];

$updatedCount = 0;
if(isset($_GET['updated']))
{
    $updatedCount = $_GET['updated'];
}*/

$fp = fopen('image_update.txt', 'w');//opens file in append mode  
fwrite($fp, '');  
fclose($fp);  


/*require_once("../ichat/admin/assets/includes/Library/SessManager.php");
require_once("../ichat/admin/assets/includes/Library/User.php");
$session = new  SessManager();*/

//require_once "check_admin.php";
require_once 'database.php';
class Upload extends database
{
    public function updateMainImage($image, $productID)
    {
		return $this->update('tb_product', ['cl_image' => $image], ['cl_product_id' => $productID]);
	}

    public function insertAdditionalImage($image, $id)
    {
        $data['cl_type'] = 'Product';
        $data['cl_product_id'] = $id;
        $data['cl_actual_name'] = $data['cl_name'] = $image;
        $data['cl_extension'] = 'jpeg';
        $data['cl_user_id'] = 1;

        return $this->insert('tb_files', $data);
    }

    public function getCurrentProduct($productID)
    {
        return $this->fetchRow('tb_product', ['cl_product_id' => $productID]);
    }

    
}

$obj = new Upload();


$productArray = array();
$dev = new Upload();	
$msg="";
if(isset($_GET['message']))
{
	$msg=$_GET['message'];
}
	/*if(isset($_FILES['csv']['tmp_name']) && is_uploaded_file($_FILES['csv']['tmp_name']))
    {
        
        $target_dir = "uploads/cenas-category/";
        $randName = date('dmYhis') . rand(10000,99999) . basename($_FILES['csv']["name"]);
        $target_file = $target_dir . $randName;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
        // Check if image file is a actual image or fake image
    
      

        // Check if file already exists
        if (file_exists($target_file)) {
            $msg.=  "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES['csv']["size"] > 500000000) {
            $msg.=  "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "csv" ) {
            $msg.=  "Sorry, only CSV files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if(trim($msg) == '')
        { */
           $csvAsArray = array_map('str_getcsv', file('507610_cennik_AB.csv'));
           $count = 1;
           ?>
           <table style="width:100%" border="1">
               <?php
               foreach($csvAsArray AS $each)
               {
               
                if($count==1)
                {
                    ?>
                    <tr><td colspan="17"><?php echo $each[0] ?></td></tr>
                    <?php
                }
                else if($count == 2)
                {
                    ?>
                    <tr>
                        <td><?php echo $count ?></td>
                        <?php
                        $columntCount = 1;
                        $columns = explode(";",$each[0]);
                        foreach($columns AS $column)
                        {
                            
                            ?>
                            <td>
                                <?php echo $column; ?>
                            </td>
                            <?php
                            $columntCount++;
                        }
                     ?>
                     <td>

                     </td>
                    </tr>
                    <?php
                }
                else
                {

                  
                    
                    ?>
                    <tr>
                        <td><?php echo $count ?></td>
                        <?php
                        $columns = explode(";",$each[0]);
                        $columntCount = 1;
                        $productID = '';
                        foreach($columns AS $column)
                        {
                            if($columntCount == 13)
                            {
                                $productID = str_replace('"', '', $column);
                            }
                            else if($columntCount == 2)
                            {
                                $dataBaseproductID = str_replace('"', '', $column);
                               
                            }
                            ?>
                            <td>
                              <?php echo $column; ?>
                            </td>

                            <?php
                            $columntCount++;
                        }

                      


                        ?>
                         <td>
                                   <?php echo $dataBaseproductID; ?>
                                </td>
                        <?php

                        if(trim($productID) != '')
                        {
                            $product = $obj->getCurrentProduct($dataBaseproductID);

                            if($product && ($product['cl_image'] != null && trim($product['cl_image']) != ''))
                            {
                                       
                                    $imageName = $product['cl_image'];
                                    if(!file_exists('../uploads/products/' . $imageName)){
                                        $data  = array('client'             => '00124119', 
                                            'login'             => 'efix.ab', 
                                            'pass'              => 'AFpdCS', 
                                            'req'               => 'image', 
                                          //  'pid'               => 'UKMIC290015;AKASS113043;KOTRAZT9008;121650;121974', 
                                            'pid'          => $productID 
                                            );

                                            // wykonujemy request
                                            $url        = 'https://xml.ab.pl/gateway.php';
                                            $curl       = curl_init();
                                            curl_setopt($curl, CURLOPT_URL, $url);
                                            curl_setopt($curl, CURLOPT_POST, true);
                                            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                                            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                                            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                                            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
                                            $result     = curl_exec($curl);
                                            $err        = curl_error($curl);
                                            $errno      = intval(curl_errno($curl));
                                            curl_close($curl);

                                            // sprawdzamy odpowiedz
                                            if (!$err) {
                                                // odpowiedz ok, request mozna parsowac
                                              //  print(htmlspecialchars($result));

                                                $ob = simplexml_load_string($result);
                                              
                                                $images = $ob->image->data;
                                              
                                                $imageCount  = 2;
                                                
                                                if(isset($images) && trim($images) != '' && is_object($images))
                                                {
                                                    foreach($images AS $data)
                                                    {


                                                        $data = 'data:image/jpeg;base64,' . $data;
                                                        if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
                                                            $data = substr($data, strpos($data, ',') + 1);

                                                            $type = strtolower($type[1]); // jpg, png, gif

                                                            if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
                                                                throw new \Exception('invalid image type');
                                                            }

                                                            $data = base64_decode($data);

                                                            if ($data === false) {
                                                                throw new \Exception('base64_decode failed');
                                                            }
                                                        } else {
                                                            throw new \Exception('did not match data URI with image data');
                                                        }

                                                        $dataBaseProductIDName = str_replace('#', '', $dataBaseproductID);
                                                        $dataBaseProductIDName = str_replace('?', '', $dataBaseProductIDName);
                                                        $dataBaseProductIDName = str_replace('&', '', $dataBaseProductIDName);
                                                      //  $imageName = 'ab_' . $dataBaseProductIDName . '_' . $imageCount . '.jpeg';
                                                        file_put_contents('../uploads/products/' . $imageName, $data);
                                                        if($imageCount == 2)
                                                        {
                                                            $updatedCount++;
                                                         //   $obj->updateMainImage($imageName, $dataBaseproductID);

                                                            $fp = fopen('image_update.txt', 'a');//opens file in append mode  
                                                            fwrite($fp, $dataBaseProductIDName . ' ' . $count . 'Updated<br/>');  
                                                            fclose($fp);
                                                        }
                                                        else
                                                        {
                                                            //$obj->insertAdditionalImage($imageName, $product['cl_id']);
                                                        }

                                                        

                                                        $imageCount++;
                                                    }
                                                    ?>
                                                    <td>
                                                        Database Updated
                                                    </td>
                                                    <?php
                                                }
                                                else
                                                {
                                                ?>
                                                <td>
                                                    No Images Found
                                                </td>
                                            <?php
                                                }

                                            } else {
                                                // problem CURLa z wykonaniem requestu
                                                var_dump($err, $errno);
                                            }

                                           
                                        }
                                            
                                        }
                                        else
                                        {
                                            ?>
                                            <td>
                                                Not Found in Database / Image already Found
                                            </td>
                                            <?php
                                        } 
                                    }
                                    else
                                    {
                                         ?>
                                            <td>
                                                Product ID is empty
                                            </td>
                                            <?php
                                    }
                
                     ?>
                    </tr>
                    <?php
                }

                 
                ?>
                <?php
                $count++;
               }

               ?>
           </table>
           <?php
          
          
       /* }
    }*/
   if($count < $start)
   {
    echo 'finished';
    echo '<br/>';
    echo $count;
    exit;
   }
?>


<script>
   // window.location.href = 'test_csv_loader?start=<?php echo ($start + 150) ?>&updated=<?php echo $updatedCount ?>';

    </script>