<?php


class Coupang extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('RestTaskCoupangServiceClient', [], 'restClient');
        $this->load->library('RestCoupangApiServiceClient', [], 'restApiClient');
        $this->load->model('DSCoupang_model', 'coupang_model');
    }

    public function index()
    {
        $this->data = ['page' => $this->getPage(__FUNCTION__), 'categories' => $this->coupang_model->findAllCategories()];
        $this->load->view('page', $this->data);
    }

    public function all()
    {
        $data = $this->coupang_model->getTable(json_decode($this->input->raw_input_stream));
        $this->response($data);
    }

    public function delete()
    {
        $data = $this->restClient->deleteDeveloper(['developers' => array_column($this->input->post('selection'), 'id')]);
        $this->response(array(
            'code' => 200,
            'data' => []
        ));
    }

    public function update()
    {
        foreach ($this->input->post('selection') as $developer) {
            $this->restClient->updateDeveloper([
                'name' => $developer['name'],
                'description' => $developer['description'],
                'id' => $developer['id']
            ]);
        }
        $this->response(array(
            'code' => 200,
            'data' => []
        ));
    }

    public function save()
    {
        if ($this->restClient->saveDeveloper([
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ])) {
            $this->response(array(
                'code' => 200,
                'data' => []
            ));
        } else {
            $this->response(array(
                'code' => 500,
                'data' => []
            ));
        }
    }

    public function categories()
    {
        $this->response(array(
            'code' => 200,
            'data' => $this->restClient->getCategories()
        ));
    }

    public function category($categoryCode = 69972)
    {
        $this->response(array(
            'code' => 200,
            'data' => $this->restApiClient->getCategory($categoryCode)
        ));
    }

    public function sendnew() {
        $responseData = $this->restApiClient->postProduct(['products' => [$this->input->post()]]);
        $sellerProducts = [];
        foreach($responseData as $rd) {
            array_push($sellerProducts, ['sellerProductId' => $rd->data]);
        }
        $this->load->model('DSCoupang_model', 'coupangModel');
        $this->coupangModel->save($sellerProducts);
        $this->response(array(
            'code' => 200,
            'data' => $this->restApiClient->postProduct(['products' => [$this->input->post()]])
        ));
    }
}
