<?php
class ControllerAppiOrder extends Controller
{
    private $prefix_list=array('OZL','FZ1','U6',"YK3",'XBT','KRKC','ADN','YENI-SERI-2024','KRK','AHY','FY1','MU66','MU31','BL2','C2','WD2');

    public function index()
    {


        $barcode = $this->request->get['barcode'];


        $query = $this->db->query("select * from product_url where barcode like '" . $barcode . "' or stock_code like '%" . $barcode . "%'");

        $this->load->model("entegrasyon/addproduct");

        if ($query->num_rows) {


            $url_list[] = array('url' => $query->row['url'],'barcode'=>$barcode,'price'=>$query->row['sale_price']);
            $result = $this->model_entegrasyon_addproduct->getProductsBulkWithRetry($url_list);

            if($result[0]['httpcode']!=404){

                echo json_encode(array('url' => $query->row['url'], 'image' => $result[0]['image'], 'cost_price' => $result[0]['price']));

            }else {
                echo json_encode(array());
            }



        }else {

            $barcode = str_replace($this->prefix_list, '', $barcode);

            $result =  $this->model_entegrasyon_addproduct->fetchTrendyolProductViaApi($barcode);

            $this->db->query("INSERT INTO `product_url` SET user_id='" . $this->user_info['user_id'] . "', `stock_code`='" . $this->db->escape($barcode) . "', `barcode`='" . $this->db->escape($barcode) . "', `url`='" . $result['link'] . "',image=>'".$result['image']."', `sale_price` ='" . $result['price'] . "', hb=1 ");

            echo  json_encode(array('url'=>$result['link'],'image'=>$result['image'],'cost_price'=>$result['price']));

        }

    }


}