<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends MY_BackendController {

    public function __construct() {
        parent::__construct();
        $this->load->model('Product_model');
    }
    
    public function index() {
        $this->view('backend/product/index', []);
    }

    public function add() {       
        $this->view('backend/product/add',[]);
    }
    
    public function insert() {
         $input = $this->input->post();
        if (!empty($input)) {
            $param_p=[];
            $param_pp=[];
            foreach($input as $k=>$v){
//                log_message('debug','k:'.$k);
                if($this->startsWith($k,'p_')){
                    $idx = str_replace('p_','',$k);
                    $param_p[$idx]=$v;
                }else{
                     $idx = str_replace('pp_','',$k);
                    $param_pp[$idx]=$v;
                }
            }     
            $newid = $this->Product_model->insert($param_p,$param_pp);
//            log_message('debug', 'newid:'.$newid);//8
            header('location: /product');
        }
    }

    public function edit() {
        $request = $this->input->post();
        $result = $this->Product_model->detail_product($request['id']);
        $this->view('backend/product/edit', ['status' => $this->Product_model->status, 'product' => $result]);
    }

    // Insert / Update
    public function save() {
        $request = $this->input->post();
        $param_p = ['name' => trim($request['p_name']), 'status' => trim($request['p_status']), 'remark' => trim($request['p_remark']),'product_category_id'=>trim($request['p_product_category_id'])];
        $param_pp = ['selling_price'=>trim($request['pp_selling_price']),'original_price'=>trim($request['pp_original_price'])];
        $this->Product_model->save([$param_p,$param_pp], [$request['pid'],$request['ppid']]);
        header('location:/product');
    }

    public function delete() {
        $request = $this->input->post();
        $ids = explode(',', $request['ids']);
//       log_message('debug','is ids array?'.is_array($ids));//true
        $this->Product_model->deleteMultiple($ids);
        header("location:/product");
    }

    public function deleteall() {
        $this->Product_model->deleteAll();
        header("location:/product");
    }

}
