<?php
    include 'vendor/autoload.php';
    use Goutte\Client;
    use Symfony\Component\HttpClient\HttpClient;
    header('Access-Control-Allow-Origin: '.$config->get('site_url'));
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

    $response           = [];
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(isset($_POST['csrf_token']) && $csrf_generator->validate($_POST['csrf_token'])) {
            $cimri = new Cimri($db, $utils, $product);
            $products         = $cimri->getProducts();

            $client = new Client(HttpClient::create(['verify_peer' => false, 'verify_host' => false]));

            foreach($products as $row) {
                if(empty($row['cimri_url'])) {
                    try{
                        $url = "https://www.cimri.com/arama?q=" . urlencode($row['title']);
                        //$url = "https://www.cimri.com/arama?q=" . urlencode($row['brand']." ".$row['model']);
                        $client->restart(); // removing all history and cookies from client to solve access denied problem
                        $crawler = $client->request('GET', $url, [], [], ['HTTP_USER_AGENT' => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"]);
                        
                        $link           = $crawler->filter('#cimri-product > article > a')->attr('href');
                        $title          = $crawler->filter('#cimri-product > article > h3')->text();
                        $offer          = $crawler->filter('#cimri-product > article > div.top-offers > a:nth-child(1)')->text();
                        $seller         = $crawler->filter('#cimri-product > article > div.top-offers > a:nth-child(1) > div')->text();

                        $price          = str_replace($seller, '', $offer);
                        $price          = str_replace(" TL", '', $price);
                        $price          = str_replace(".", '', $price);
                        $price          = str_replace(",", '.', $price);
    
                        $db->query("INSERT INTO `cf_cimri_products` (`status`, `product_title`, `product_id`, `cimri_price`, `cimri_seller`, `cimri_url`, `date_added`, `date_modified`) VALUES (1, :product_title, :product_id, :cimri_price, :cimri_seller, :cimri_url, NOW(), NOW())",
                        array(':product_title'=>$title, ':cimri_url'=>"https://www.cimri.com".$link, ':cimri_seller'=>$seller, ':cimri_price'=>$price, ':product_id'=>$row['product_id_']));
                    } catch(Exception $e) {
                        // Node list is empty
                        //echo $e;
                    }
                    sleep(1);
                }
                
            }
            $response = array('status'=>true, 'message'=>"Ürünler güncellendi!");
        }else{
            $response = array('status'=>false, 'message'=>"Hatalı CSRF Token!");
        }
    }else{
        $response = array('status'=>false, 'message'=>"Hatalı İstek!");
    }

    echo json_encode($response);