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

class Detail extends Api_Controller
{

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

    public function getDetailData()
    {
        $id = $this->input->post('id');
        $item_code = $this->input->post('item_code');

        if (!isset($id, $item_code)) {
            $this->FailedResponse('Invalid Param');
        }
        $data = $this->getDetailModel()->get_by(array(
            ID => $id,
            Item_Code => $item_code
        ), false);
        if ($data) {
            $this->SuccessResponse($data);
        } else {
            $this->FailedResponse("There is no item yet");
        }
    }

    public function updateSubData()
    {
        //ItemCode~Location~Supplier~Quantity~UOM~RunningNumber
        $item_code = $this->input->post('item_code');
        $location = $this->input->post('location');
        $warehouse = $this->input->post('warehouse');
        $supplier = $this->input->post('supplier');
        $quantity = $this->input->post('quantity');
        $uom = $this->input->post('uom');
        $running_no = $this->input->post('running_no');
        $scanned_date = $this->input->post('scanned_date');

        if (!isset($item_code, $location, $warehouse, $supplier, $quantity, $uom, $running_no, $scanned_date)) {
            $this->FailedResponse('Invalid Param');
        }

        $data = $this->getDetailModel()->get_by(array(
            Item_Code => $item_code,
            Serial_Number => $running_no
        ), true);

        if (!$data) {
            $this->FailedResponse("System has no item for your request");
        }

        $details_id = $data[Details_ID];
        $id = $data[ID];

		$data_back = $data;
        $data = array(
            Quantity_Scanned => $quantity,
            Destination_Loc => $location,
            Destination_WH => $warehouse,
            Date_Scanned => $scanned_date
        );

        $this->getDetailModel()->update($data, $details_id);

		$log_data = $this->getLogModel()->get_by(array(
            ID => $id
        ), true);
        $this->updateMainData($id, $scanned_date);

        $res = $this->updateServer($id, $details_id); // 
		
		if($res === TRUE){
			$this->TextResponse("Updated data successfully");
		} else {
			$this->getDetailModel()->update($data_back, $details_id);
			$this->getLogModel()->update($log_data, $id);
			$this->FailedResponse("Update failed");
		}
    }

    public function addSubData()
    {
        //ItemCode~Location~Supplier~Quantity~UOM~RunningNumber
        $item_code = $this->input->post('item_code');
        $location = $this->input->post('location');
        $warehouse = $this->input->post('warehouse');
        $supplier = $this->input->post('supplier');
        $quantity = $this->input->post('quantity');
        $uom = $this->input->post('uom');
        $running_no = $this->input->post('running_no');
        $scanned_date = $this->input->post('scanned_date');
        $id = $this->input->post('id');


        if (!isset($item_code, $location, $warehouse, $supplier, $quantity, $uom, $running_no, $scanned_date, $id)) {
            $this->FailedResponse('Invalid Param');
        }

        $log_data = $this->getLogModel()->get_by(array(
            ID => $id
        ), true);

        if (!$log_data) $this->FailedResponse("Unknown issue occurred");

        $data = array(
            Serial_Number => $running_no,
            Item_Code => $item_code,
            Quantity_Scanned => $quantity,
            UOM => $log_data[UOM],
            Reference_No => $log_data[Reference_No],
            ID => $id,
            Date_Scanned => $scanned_date,
            Original_Loc => $location,
            Destination_Loc => $log_data[Destination_Loc],
            Original_WH => $warehouse,
            Destination_WH => $log_data[Destination_WH],
        );

        $details_id = $this->getDetailModel()->save($data);
        if ($details_id) {
		    
			$this->updateMainData($id, $scanned_date);

			$res = $this->updateServer($id, $details_id);
			if($res===TRUE){
	            $this->TextResponse("Added item successfully");
			} else {
				$this->getDetailModel()->delete($details_id);
				$this->getLogModel()->update($log_data, $id);
				$this->FailedResponse('Something went wrong.');
			}
        } else {
            $this->FailedResponse('Something went wrong.');
        }
    }

    public function clearSubData()
    {
        $details_id = $this->input->post('details_id');

        if (!isset($details_id)) {
            $this->FailedResponse('Invalid Param');
        }

        $data = $this->getDetailModel()->get_by(array(
            Details_ID => $details_id,
        ), true);

        if (!$data) {
            $this->FailedResponse("Systen has no item for your request");
        }

        $id = $data[ID];
        $res = $this->updateServer($id, $details_id, true);

		if($res===TRUE){
			$data = array(
				Quantity_Scanned => 0,
				Destination_Loc => "",
				Destination_WH => "",
				Date_Scanned => ""
			);


			$this->getDetailModel()->update($data, $details_id);
			$this->updateMainData($id, null);

			$this->TextResponse("Removed data successfully");
		} else {
			$this->FailedResponse("Removed data failed");
		}
    }

    public function deleteSubData()
    {
        $details_id = $this->input->post('details_id');

        if (!isset($details_id)) {
            $this->FailedResponse('Invalid Param');
        }

        $data = $this->getDetailModel()->get_by(array(
            Details_ID => $details_id,
        ), true);

        if (!$data) {
            $this->FailedResponse("System has no item for your request");
        }

        $id = $data[ID];

        $res = $this->updateServer($id, $details_id, true);
		if($res===TRUE){
			$this->getDetailModel()->delete($details_id);
			$this->updateMainData($id, null);
		 
			$this->TextResponse("Removed data successfully");
		} else {
			$this->FailedResponse("Removed data failed");
		}
    }

    protected function updateMainData($id, $scanned_date)
    {
        $log_data = $this->getLogModel()->get_by(array(
            ID => $id
        ), true);

        if (!$log_data) return false;

        $item_array = $this->getDetailModel()->get_by(array(
            ID => $id,
        ), false);
        $qty = 0;
        if ($item_array) {
            foreach ($item_array as $item) {
                $qty = $qty + $item[Quantity_Scanned];
            }
        }

        $status = $log_data[Status];
        if ($qty >= $log_data[Quantity])
            $status = STATUS_CLOSED;
        else if ($status != STATUS_LOCKED)
            $status = STATUS_OPEN;
        $data = array(
            Quantity_Scanned => $qty,
            Status => $status
        );

        if ($scanned_date) {
            $data[Date_Scanned] = $scanned_date;
        }
        return $this->getLogModel()->update($data, $id);
    }

    protected function updateServer($id, $details_id, $is_delete = false)
    {
        //if($is_delete)            return false; // 
   
            if( $is_delete){
                $api = ASPX_SERVER."Mobile_Inventory_Transmitter_delete.aspx";
                // echo "Deleting via aspx";
            } else {
                $api = ASPX_SERVER."Mobile_Inventory_Transmitter.aspx";
            }
            $url  = $api.'?Details_ID=' . $details_id;
            return $this->callUrl($url, true);
            
    }

    public function getQty(){

        $item_code = $this->input->post('item_code');
        $location = $this->input->post('location');
        $warehouse = $this->input->post('warehouse');
        $uom = $this->input->post('uom');

        if (!isset($location, $warehouse, $uom)) {
            $this->FailedResponse('Invalid Param');
        }

        $ch = curl_init();

        $url = ASPX_SERVER."Mobile_Inventory_Quantity.aspx?";
        $parma = "item_code=" . urlencode($item_code). "&"
            . "location=" . urlencode($location) . "&"
            . "warehouse=" . urlencode($warehouse) . "&"
            ."uom=" . urlencode($uom);

        
        $url = $url . $parma;

        logFile('>> calling url >>' , $url);
        // echo $url ."<br/>";
        $header = array('User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    

        $data = curl_exec($ch);

        curl_close($ch);

        if($data){
            header('Content-Type: application/json');
            echo $data;
            die();
        } else {
            $this->TextResponse("Something went wrong");
        }
    }
}