<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
class Outlet_API extends CI_Controller
{
    var $main_menu_name = "";
    var $sub_menu_name = "";
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('common_model');
        //$this->load->model('api_model');
        header('Content-Type: application/json');
        if (!isset($_SERVER['CONTENT_TYPE'])) {
            $this->output
                 ->set_content_type('application/json')
                 ->set_status_header(415 )
                 ->set_output(json_encode(array(
                     'error' => 'Content Type undefined',
                     'message' => 'The type of content you are trying to submit must be defined.'
                 )));
            exit();
        }

        if ($_SERVER['CONTENT_TYPE'] !== "application/json" && $_SERVER['CONTENT_TYPE'] !== "application/json; charset=utf-8") {
            $this->output
                 ->set_content_type('application/json')
                 ->set_status_header(415 )
                 ->set_output(json_encode(array(
                     'error' => 'Invalid content type',
                     'message' => 'The type of content ('.$_SERVER['CONTENT_TYPE'].') you are trying to submit is not acceptable. JSON required.'
                 )));
            exit();
        }
        $_POST = json_decode(file_get_contents("php://input"), true);
    }
    public function index()
    {
        $data = array(
            "status" => 0,
            "msg" => "Error",
            "err_code" => "error-200-a"
        );
        echo json_encode($data);
    }

    /*/add grn/*/
    public function create_grn(){
        $location_key           = $this->input->post('authKey');
        $receiver_id            = $this->input->post('receiver_id');
        $origin_type            = $this->input->post('origin_type');
        $origin_id              = $this->input->post('origin_id');
        $date_time              = $this->input->post('date_time');
        $uuid                   = $this->input->post('uuid');
        $ref_no                   = $this->input->post('ref_no');
        $items                  = $this->input->post('items');
        $total_vale                   = $this->input->post('total_vale');
        /* Start validation */
        $auth = $this->auth($location_key);
        if(!$auth['success']){
            http_response_code(401);
            return;
        }
        if (empty($items)) {
            http_response_code(400);
            echo "Items is empty.";
            return;
        }
        if (!$receiver_id) {
            http_response_code(400);
            echo "Receiver ID is not provided.";
            return;
        }
        if (!$origin_type) {
            http_response_code(400);
            echo "Origin type is not provided.";
            return;
        }
        if (!$origin_id) {
            http_response_code(400);
            echo "Origin ID is not provided.";
            return;
        }
        if (!$date_time) {
            http_response_code(400);
            echo "Date time is not provided.";
            return;
        }
        if (!$uuid) {
            http_response_code(400);
            echo "UUID is not provided.";
            return;
        }
        $this->load->model('purchases_model');
        //Validation Process 
        $products = array();
        $this->db->select('product_mat_id,product_mat_code');
        $this->db->from('product_material');
        $query = $this->db->get();
        $products_raw = $query->result();
        foreach($products_raw as $itm){
            $products[$itm->product_mat_code] = $itm;
        }
        $product_codes_not_found = array();
       /* /end mapping/*/
       foreach($items as $item){
            if(isset($products[$item['product_code']])){
            }else{
                $product_codes_not_found[] = $item['product_code'];
            }
        }
         /*/before save grn items/*/
        if(!empty($product_codes_not_found)){
            echo json_encode(array(
                'error' => 'Missing items found',
                'data'  => $product_codes_not_found
            ));
            return;
        }
        // validation process end
        $sender = $auth['data'];
       $ori_data = array(
       'reference_no' => $this->common_model->gen_ref_number('id','purchases',"UGRN") ,
       'warehouse_id' => 4,
       'supplier_id'  => 4,
       'date'         => date("Y-m-d H:i:s"),
       'note'         => "",
       'total'        => $total_vale,
       'grand_total'  => $total_vale,
       'discount'     => 0,
       'discount_cal' => 0,
	   'supp_invocie_no'=>$ref_no,
	   'invoice_type'=>3
        );
        $this->db->trans_start();
        $grn_id = $this->purchases_model->save_grn_header($ori_data);
        /*/mapping pro/*/
        $products = array();
        $this->db->select('product_mat_id,product_mat_code');
        $this->db->from('product_material');
        $query = $this->db->get();
        $products_raw = $query->result();
        foreach($products_raw as $itm){
            $products[$itm->product_mat_code] = $itm;
        }
        $product_codes_not_found = array();
       /* /end mapping/*/
        foreach($items as $item){
            if(isset($products[$item['product_code']])){
                $itm_data = array(
                    'purchase_id'    => $grn_id,
                    'product_id' => $products[$item['product_code']]->product_mat_id,
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['unit_value'],
                    'sub_total' => $item['unit_value']*$item['quantity'],
                    'product_code' => $item['product_code_ref'],
                    'product_name' => $item['product_name'],
                    'batch_code'=>$item['batch_no']
                );
                $grn_item_data[] = $itm_data;
            }else{
                $product_codes_not_found[] = $item['product_code'];
            }
        }
        /*/before save grn items/*/
        if(!empty($product_codes_not_found)){
            echo json_encode(array(
                'error' => 'Missing items found',
                'data'  => $product_codes_not_found
            ));
            return;
        }
       foreach($grn_item_data as $row2){
          $num_of_rec = $this->purchases_model->save_grn_item($row2); 
       }
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE){
            $this->common_model->add_user_activitie("GRN saved - failed");
            $this->output
                 ->set_content_type('application/json')
                 ->set_status_header(409)
                 ->set_output(json_encode(array(
                     'error' => 'Duplicate entry',
                     'message' => 'The resource you are trying to create already exists.'
                 )));
        } else {
            //$this->common_model->add_user_activitie("GRN saved - $sender->id/id#$grn_id");
            http_response_code(200);
        }
    }
    function auth($location_key){
        if(!$location_key){
            return array(
                'success' => false
            );
        }
        $this->db->select('*');
        $this->db->from('warehouses');
        $this->db->where('auth_code',$location_key);
        $query = $this->db->get();
        $result = $query->row();
        return array(
                'success'   => true,
                'data'      => $result
        );
    }
}

