<?php

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

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
require APPPATH . 'libraries/REST_Controller.php';

class Work_order extends REST_Controller {

  function __construct()
  {
    parent::__construct();
    // Construct the parent class
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
      die();
    }

    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");
    ini_set("allow_url_fopen", "1");
    

    //      Load Models
    $this->load->model('User_model', 'User');
    $this->load->model('Sales_quotation_model','Sales_quotation');
    $this->load->model('Work_order_model','Work_order');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Settings_model', 'Settings');
  }
  public function index_get()
  {
    //     Default Method
    $this->select_get();
  }
  public function create_post()
  {
    $terms_and_condition_templates = $this->Settings->select_terms_and_condition_templates('',array("terms_type"=>'Work Order'))->result();
    $i = 0;
    $terms_new = array();
    foreach ($terms_and_condition_templates as $row) {
      $terms_new[$i]['description'] = $row->description;
      $i++;
    }
    if(sizeof($terms_new)>0){
      $data['terms_and_conditions'] = serialize($terms_new);
    }

    if($this->post('user_id')!="" && $this->post('user_id') !== NULL) {

      $user_id = $this->post('user_id');
      $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$user_id));
      if ($employee_data->num_rows() == 1) {
        // Generate Work order No
        $data['branch_id'] = $employee_data->row()->branch_id;
        $this->db->where('wo.branch_id',$data['branch_id']);
        $last_data = $this->Work_order->select_work_orders("max(wo.order_no) as max_order_no");
        if($last_data->num_rows()==1){
          $data['order_no'] = ($last_data->row()->max_order_no)+1;
        }else{
          $data['order_no'] = 1;
        }

        $data['order_date'] = date('Y-m-d',strtotime($this->post('order_date')));
        $data['customer_name'] = $this->post('customer_name');
        $data['customer_address'] = $this->post('address');
        $data['site_coordinator'] = $this->post('site_coordinator');
        $data['quotation_id'] = $this->post('quotation_id');
        $data['project_start_date'] = date('Y-m-d',strtotime($this->post('project_start_date')));
        $data['state'] = $this->post('state');
        $data['bank_account'] = $this->post('bank_account');
        $data['grand_total_amount'] = $this->post('grand_total');
        $data['discount_amount'] = $this->post('discount_amount');
        $data['total_order_amount'] = $this->post('total_order_amount');
        $data['created_date']  = date('Y-m-d H:i:s');
        $data['created_by'] = $user_id;

        $schedule = array();
        $payment_schedules = json_decode($this->post('payment_schedules'), true);
        for ($j = 0; $j < sizeof($payment_schedules); $j++) {
          $schedule[$j]['particulars'] = $payment_schedules[$j]['particulars'];
          $schedule[$j]['percent'] = $payment_schedules[$j]['percent'];
          $schedule[$j]['amount'] = $payment_schedules[$j]['amount'];
          $schedule[$j]['remarks'] = $payment_schedules[$j]['remarks'];
        }
        if(sizeof($schedule)){
          $data['payment_schedule'] = serialize($schedule);
        }

        $json_data = $this->post('items');
        $items = json_decode($json_data, true);
        if (!empty($items)) {
          $result = $this->Work_order->insert_work_order($data);
          if($result['status']==1){

            $items_count = sizeof($items);
            $item_data['order_id'] = $result['insert_id'];
            for ($i = 0; $i < $items_count; $i++) {
              $item_data['area_type'] = $items[$i]['area'];
              $item_data['quantity'] = $items[$i]['quantity'];
              $item_data['warranty'] = $items[$i]['warranty'];
              $item_data['unit_price'] = $items[$i]['unit_price'];
              $item_data['total_price'] = $items[$i]['total_price'];
              $result_items = $this->Work_order->insert_work_order_item($item_data);
            }
          }
          $message = [
            'status' => TRUE,
            'message' => 'Work Order Added Successfully'
          ];
          $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
        }else{
          $message = [
            'status' => FALSE,
            'message' => 'Items Empty'
          ];
          $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'User Details Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Template ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['wo.created_by'] = $user_id;
      $work_orders = $this->Work_order->select_work_orders("wo.*,u.user_alias,b.*,sq.quotation_no,u2.user_alias as site_coordinator_name",$data);

      $message = array();
      $j = 0;
      if ($work_orders->num_rows() > 0){
        foreach ($work_orders->result() as $row):

          $print_url=base_url().'download/work_order?id='.$row->order_id."&user=".$user_id."&token=".md5($user_id.$row->order_id.$user_id)."&date=".$row->order_date;
          $item_details = '';
          // $items = $this->Work_order->select_work_order_items("woi.*,",array("woi.order_id"=>$row->order_id))->result();


          $message[$j]['order_id'] = $row->order_id;
          $message[$j]['order_no'] = '#'.$row->workorder_prefix.'-'.$row->order_no.'';
          $message[$j]['date'] = date('d-m-Y',strtotime($row->order_date));
          $message[$j]['quotation_no'] = '#'.$row->quotation_prefix.'-'.$row->quotation_no;
          if($row->project_start_date!='0000-00-00'){
            $message[$j]['project_start_date'] = date('d-m-Y',strtotime($row->project_start_date));
          }else{
            $message[$j]['project_start_date'] = '';
          }
          $message[$j]['customer_name'] = $row->customer_name;
          $message[$j]['customer_address'] = $row->customer_address;
          $message[$j]['site_coordinator'] = $row->site_coordinator_name;
          $message[$j]['created_by'] = $row->user_alias;
          $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
          $message[$j]['print_url'] = $print_url;

          $j++;
        endforeach;
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No Sales Quotations Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }

      $json_data['status'] = TRUE;
      $json_data['data'] = $message;
      $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_details_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('order_id')!="" && $this->get('order_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['wo.order_id'] = $this->get('order_id');
      $work_order = $this->Work_order->select_work_orders("wo.*,u.user_alias,b.*,sq.quotation_no,u2.user_alias as site_coordinator_name",$data);

      $message = array();
      $j = 0;
      if ($work_order->num_rows()==1){
        $row = $work_order->row();

          $message['order_id'] = $row->order_id;
          $message['order_no'] = '#'.$row->workorder_prefix.'-'.$row->order_no;
          $message['date'] = date('d-m-Y',strtotime($row->order_date));
          $message['quotation_no'] = '#'.$row->quotation_prefix.'-'.$row->quotation_no;
          if($row->project_start_date!='0000-00-00'){
            $message['project_start_date'] = date('d-m-Y',strtotime($row->project_start_date));
          }else{
            $message['project_start_date'] = '';
          }
          $message['customer_name'] = $row->customer_name;
          $message['customer_address'] = $row->customer_address;
          $message['site_coordinator'] = $row->site_coordinator_name;
          $message['created_by'] = $row->user_alias;
          $message['created_date'] = date('d-m-Y',strtotime($row->created_date));
          $items_array = array();
          $items = $this->Work_order->select_work_order_items("woi.*",array("woi.order_id"=>$row->order_id))->result();
          foreach ($items as $key => $value) {
            $items_array[$j]['item_id'] = $value->item_id;
            $items_array[$j]['area'] = $value->area_type;
            $items_array[$j]['quantity'] = $value->quantity;
            $items_array[$j]['unit_price'] = $value->unit_price;
            $items_array[$j]['total_price'] = $value->total_price;
            $items_array[$j]['warranty'] = $value->warranty;

            $j++;
          }
          $message['items'] = $items_array;

      } else {
        $message = [
          'status' => FALSE,
          'message' => 'Sales Quotation Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }

      $json_data['status'] = TRUE;
      $json_data['data'] = $message;
      $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Quotation ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
}
