<?php

class ControllerDevCategory extends Controller
{
    private $error = array();
    private $token_data;


    public function test()
    {
        $query = $this->db->query("select * from oc_category");


        foreach ($query->rows as $row) {


            $this->db->query("UPDATE oc_category SET ty='".$row['category_id']."' where id='".$row['id']."'");

        }

    }

    public function add_color()
    {

        $query = $this->db->query("SELECT * FROM `oc_attribute_value` WHERE `attribute_id` = '147'");

        $id=999999;
        foreach ($query->rows as $row) {


           $query = $this->db->query("select * from `oc_attribute_value` where `name`='".$row['name']."' and attribute_id=47");
           if(!$query->num_rows){
               $this->db->query("insert into `oc_attribute_value` SET attribute_id=47, attribute_value_id='".$id."', `name`='".$row['name']."'  ");
               $id++;
           }


        }

    }


    public function auto_match()
    {
        $matched = 0;
        $unmatched = 0;
        $code = $this->request->get['code'];

        $query = $this->db->query("select * from oc_category where $code = 0 ");


        foreach ($query->rows as $row) {

           if( $this->check($row,$code)){


               $matched++;
           }else {
               $unmatched++;
           }

        }

        echo $matched . ' adet kategori eşleşti<br>'.$unmatched.' adet kategori eşleşmedi';

    }


    private function check($category, $code)
    {



        $lastItems = explode('>', $category['name']);

        $lastItems = explode(' ', end($lastItems));


        $table = "categories_" . $code;
        $sql = "select * from $table";


        $searchItems=array();
        foreach ($lastItems as $lastItem) {
            if($lastItem){
                $searchItems[]=$lastItem;
            }
        }

        foreach ($searchItems as $index => $item) {

                if ($index == 0) {

                    $sql .= " where name like '%" . $item . "%'";

                } else {

                $sql .= " and name like '%" . $item . "%'";


        }
    }


        $query = $this->db->query($sql);
        if ($query->num_rows == 1) {

            $this->db->query("update oc_category SET $code='".(int)$query->row['category_id']."' where id='".$category['id']."'");

           return true;

        }else {
            return false;
        }


    }


}
