<?php
    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']) && $anticsrf->validate($_POST['csrf_token'])) {
            if(isset($_POST['q']) && !empty($_POST['q'])) {
                $q = trim(strip_tags($_POST["q"]));
                $result = array();

                $products = $product->getProducts(array('search_keywords' => $q, 'offset' => 0, 'limit' => 10));
                $categories = $product->getCategories(array('search_keywords' => $q));
                $brands = $product->getBrands(array('search_keywords' => $q));

                foreach($products as $row){ 
                    $item = array(
                        'id'                     => $row['id'],
                        'title'                  => $row['title'],
                        'type'                   => 'product',
                        'url'                    => $row['url']
                    );
                    array_push($result, $item);
                }

                foreach($categories as $row){ 
                    $item = array(
                        'id'                     => $row['id'],
                        'title'                  => $row['title'],
                        'type'                   => 'category',
                        'url'                    => $row['url']
                    );
                    array_push($result, $item);
                }

                foreach($brands as $row){ 
                    $item = array(
                        'id'                     => $row['id'],
                        'title'                  => $row['title'],
                        'type'                   => 'brand',
                        'url'                    => $row['url']
                    );
                    array_push($result, $item);
                }
        
                $response = array('status'=>true, 'result'=>$result);
            }else{
                $response = array('status'=>false, 'message'=>"Lütfen anahtar kelime giriniz.");
            }
        }else{
            $response = array('status'=>false, 'message'=>"Hatalı CSRF Token!");
        }
    }else{
        $response = array('status'=>false, 'message'=>"Hatalı İstek!");
    }

    echo json_encode($response);