<?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'])) {
            $akakce = new Akakce($db, $utils, $product);
            $products         = $akakce->getProducts(array('offset'=>0, 'limit'=>1));

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

            foreach($products as $row) {
                if(empty($row['akakce_url'])) {
                    try{
                        $url = "https://www.akakce.com/arama/?q=" . urlencode($row['title']);
                        $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('#APL > li:nth-child(1) > a')->attr('href');
                        $title          = $crawler->filter('#APL > li:nth-child(1) > a > span > h3')->text();
                        $offer          = $crawler->filter('#APL > li:nth-child(1) > div > ul > li.b > a > span.pb_v8 > span')->text();
                        //$seller         = $crawler->filter('#akakce-product > article > div.top-offers > a:nth-child(1) > div')->text();
                        $seller         = "";

                        $price          = str_replace('.', $offer);
                        $price          = str_replace(" TL", '', $price);
                        $price          = str_replace(",", '.', $price);
                        $price          = str_replace("<i>", '', $price);
                        $price          = str_replace("</i>", '', $price);

                        echo $title;
                        echo $price;
    
                        $db->query("INSERT INTO `cf_akakce_products` (`status`, `product_title`, `product_id`, `akakce_price`, `akakce_seller`, `akakce_url`, `date_added`, `date_modified`) VALUES (1, :product_title, :product_id, :akakce_price, :akakce_seller, :akakce_url, NOW(), NOW())",
                        array(':product_title'=>$title, ':akakce_url'=>"https://www.akakce.com".$link, ':akakce_seller'=>$seller, ':akakce_price'=>$price, ':product_id'=>$row['product_id_']));
                    } catch(Exception $e) {
                        // Node list is empty
                        var_dump($client->getResponse()->getContent());
                    }
                    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);