<?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 = $row['cimri_url'];
                        $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"]);
                        
                        $offer          = $crawler->filter('#main_container > div > div.s98wa6g-0.feTYBN > div:nth-child(2) > div.s1a29zcm-7.dPVoLl > div.s1wytv2f-0.bpjMIm > div.s1wytv2f-1.FzQtN > a.notOnlyApp.s1wl91l5-0.cZnMAi > span:nth-child(3)')->text();
                        $seller         = $crawler->filter('#main_container > div > div.s98wa6g-0.feTYBN > div:nth-child(2) > div.s1a29zcm-7.dPVoLl > div.s1wytv2f-0.bpjMIm > div.s1wytv2f-1.FzQtN > a.notOnlyApp.s1wl91l5-0.cZnMAi > span:nth-child(2)')->text();

                        $price          = str_replace(" TL", '', $offer);
                        $price          = str_replace(".", '', $price);
                        $price          = str_replace(",", '.', $price);
    
                        if($price > 0) {
                            $db->query("UPDATE `cf_cimri_products` SET `cimri_price`=:cimri_price, `cimri_seller`=:cimri_seller, `date_modified`=NOW() WHERE id=:id",
                            array(':cimri_seller'=>$seller, ':cimri_price'=>$price, ':id'=>$row['id']));
                        }
                        
                    } catch(Exception $e) {
                        // Node list is empty
                        //echo $e;
                    }
                    sleep(1);
                }
                
            }
            $response = array('status'=>true, 'message'=>"Fiyatlar güncellendi!");
        }else{
            $response = array('status'=>false, 'message'=>"Hatalı CSRF Token!");
        }
    }else{
        $response = array('status'=>false, 'message'=>"Hatalı İstek!");
    }

    echo json_encode($response);