<?php

class DSCoupang_model extends MY_Model
{

    private $id;
    private $sellerProductId;
    private $sellerProductName;
    private $displayCategoryCode;
    private $categoryId;
    private $productId;
    private $vendorId;
    private $mdId;
    private $mdName;
    private $saleStartedAt;
    private $saleEndedAt;
    private $brand;
    private $statusName;
    private $createdAt;


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

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

    public function selectClause()
    { }

    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('createdAt', 'desc')
            // ->select('ds_amazon.*, c.title category, c.link categoryLink, v.title video, v.link videoLink')
            ;
        return $this->db->get('ds_coupang')->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();
    }

    public function save($rows) {
        return $this->db->insert_batch('ds_coupang', $rows);
    }
}
