<?php

class DSAmazon_model extends MY_Model
{

    private $id;
    private $asin;
    private $price;
    private $detail;
    private $spec;
    private $video_id;
    private $category_id;
    private $created_at;


    private $currentPage = 1;
    private $perPage = 100;

    public function __construct()
    {
        parent::__construct();
    }

    public function selectClause()
    { }

    private function getCategoryPath($categories) {
        $categoryNames = [];
        foreach($categories as $category) {
            array_push($categoryNames, $category->title);
        }
        return implode(' > ', $categoryNames);
    }

    public function save($res)
    {
        $video_id = 0;
        $category_id = 0;
        $category = end($res->data->category);
        $category->title_dp = $this->getCategoryPath($res->data->category);
        $video = $res->data->description->videos;
        if (!empty($category->title)) {
            $query = $this->db->get_where('ds_category', ['title' => $category->title]);
            if ($query->num_rows()) {
                $this->db->where('id', $query->row()->id)->update('ds_category', $category);
                $category_id = $query->row()->id;
            } else {
                $this->db->insert('ds_category', $category);
                $category_id = $this->db->insert_id();
            }
        }

        if (!empty($video->title)) {
            $query = $this->db->get_where('ds_video', ['title' => $video->title]);
            if ($query->num_rows()) {
                $this->db->where('id', $query->row()->id)->update('ds_video', $video);
                $video_id = $query->row()->id;
            } else {
                $this->db->insert('ds_video', $video);
                $video_id = $this->db->insert_id();
            }
        }

        $img = '';
        if (!empty($res->data->img)) {
            $data = explode(',', $res->data->img);
            $ext = explode(';', explode('/', $data[0])[1])[0];

            $targetPath = FCPATH . 'upload/amz/' . date('Y/m/d/') . $res->data->asin . '.' . $ext;
            $img = '/upload/amz/' . date('Y/m/d/') . $res->data->asin . '.' . $ext;
            if(!is_dir(FCPATH . 'upload/amz/' . date('Y/m/d/'))) {
                mkdir(FCPATH . 'upload/amz/' . date('Y/m/d/'), 0775, true);
            }
            if(file_exists($targetPath)) {
                unlink($targetPath);
            }           

            $content = base64_decode($data[1]);
            $file = fopen($targetPath, "wb");
            fwrite($file, $content);
            fclose($file);
        }

        $query = $this->db->get_where('ds_amazon', ['asin' => $res->data->asin]);


        $this->load->model('DSAmazonOption_model', 'optionModel');

        if(empty($res->data->price)) $res->data->price = 0;
        if ($query->num_rows()) {
            $this->db->where('asin', $res->data->asin)->update('ds_amazon', [
                'title' => $res->data->title,
                'stock' => $res->data->stock,
                'price' => $res->data->price,
                'detail' => $res->data->description->content,
                'spec' => $res->data->description->spec,
                'video_id' => $video_id,
                'img' => $img ? $img : $query->row()->img,
                'category_id' => $category_id,

                'seller' => $res->data->seller->title,
                'seller_uri' => empty($res->data->seller->link)?'':$res->data->seller->link
            ]);
            if(!empty($res->colors)) {
                $this->optionModel->save($res->colors, $res->colorASIN, 'color', $query->row()->id);
            }
        } else {
            $this->db->insert('ds_amazon', [
                'asin' => $res->data->asin,
                'title' => $res->data->title,
                'stock' => $res->data->stock,
                'price' => $res->data->price,
                'detail' => $res->data->description->content,
                'spec' => $res->data->description->spec,
                'video_id' => $video_id,
                'img' => $img,
                'category_id' => $category_id, 
                'seller' => $res->data->seller->title,
                'seller_uri' => empty($res->data->seller->link)?'':$res->data->seller->link
            ]);
            if(!empty($res->colors)) {
                $this->optionModel->save($res->colors, $res->colorASIN, 'color', $this->db->insert_id());
            }
        }
    }

    public function getTable()
    {
        $this->dateRange = [strtotime($this->input->get('dateRange')[0]), strtotime($this->input->get('dateRange')[1])];
        $this->perPage = $this->input->get('limit');
        if ($this->input->get('offset')) {
            $this->currentPage = $this->input->get('offset') / $this->per_page + 1;
        }
        $preBookingResult = $this->getTableResult();
        $preBookingResultsCount = $this->getTableResultsCount();
        return array('total' => $preBookingResultsCount, 'rows' => ($preBookingResultsCount ? $preBookingResult : []));
    }

    private function getTableResult()
    {
        $this->getTableClause();
        $this->db->offset(($this->currentPage - 1) * $this->perPage);
        $this->db->limit($this->perPage);
        $this->db->order_by('created_at', 'desc')
        ->select('ds_amazon.*, c.title_dp category, c.link categoryLink, v.title video, v.link videoLink');
        return $this->db->get('ds_amazon')->result();
    }

    private function getTableClause()
    {
        $this->db->join('ds_category c', 'ds_amazon.category_id=c.id', 'left')
        ->join('ds_video v', 'ds_amazon.video_id=v.id', 'left');

        if ($this->input->post('keyword')) {
            $this->db->where('asin', $this->input->post('keyword'));
            $this->db->or_where('title', $this->input->post('keyword'));
        }

        if ($this->dateRange[0]) {
            $this->db
                ->where('created_at >=', date('Y-m-d', $this->dateRange[0]))
                ->where('created_at <', date('Y-m-d', strtotime('+1 day', $this->dateRange[1])));
        }


        if ($this->input->get('searchName') == 'boxCode') {
            $this->db->where('box_code', $this->input->get('searchWord'));
        }
    }

    private function getTableResultsCount()
    {
        $this->getTableClause();
        $this->db->from('ds_amazon');
        return $this->db->count_all_results();
    }

    public function findAllCategories() {
        return $this->db->select('id, title')->get('ds_category')->result();
    }
}
