<?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 Sales_quotation 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 select_templates_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $quotation_templates = $this->Sales_quotation->select_quotation_templates("sqt.*",);

      $message = array();
      $j = 0;
      if ($quotation_templates->num_rows() > 0){
        foreach ($quotation_templates->result() as $row):
          $message[$j]['template_id'] = $row->template_id;
          $message[$j]['template_no'] = $row->template_no;
          $message[$j]['title'] = $row->title;
          $message[$j]['sub_title'] = $row->sub_title;
          $message[$j]['description'] = $row->description;
          $message[$j]['products'] = $row->products;
          $message[$j]['unit_price'] = $row->unit_price;
          $message[$j]['warranty'] = $row->warranty;
          $message[$j]['method_of_application'] = $row->method_of_application;
          $message[$j]['notes'] = $row->notes;
          $message[$j]['created_by'] = $row->created_by;
          $message[$j]['created_date'] = $row->created_date;
          $message[$j]['delete_status'] = $row->delete_status;

          $j++;
        endforeach;
      }
      $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_template_details_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('template_id')!="" && $this->get('template_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $message = array();
      $quotation_templates = $this->Sales_quotation->select_quotation_templates("sqt.*",array("sqt.template_id"=>$this->get('template_id')));
      if($quotation_templates->num_rows()==1){

        if ($quotation_templates->num_rows() == 1){
          $row = $quotation_templates->row();
          $message['template_id'] = $row->template_id;
          $message['template_no'] = $row->template_no;
          $message['title'] = $row->title;
          $message['sub_title'] = $row->sub_title;
          $message['description'] = $row->description;
          $message['products'] = $row->products;
          $message['unit_price'] = $row->unit_price;
          $message['warranty'] = $row->warranty;
          $message['method_of_application'] = $row->method_of_application;
          $message['notes'] = $row->notes;
          $message['created_by'] = $row->created_by;
          $message['created_date'] = $row->created_date;
          $message['delete_status'] = $row->delete_status;
        }

        $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' => 'Template Details Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) 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 create_post()
  {
    $terms_and_condition_templates = $this->Settings->select_terms_and_condition_templates('',array("terms_type"=>'Sales Quotation'))->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 Quotation No
        $data['branch_id'] = $employee_data->row()->branch_id;
        $this->db->where('sq.branch_id',$data['branch_id']);
        $last_data = $this->Sales_quotation->select_quotations("max(sq.quotation_no) as max_quotation_no");
        if($last_data->num_rows()==1){
          $data['quotation_no'] = ($last_data->row()->max_quotation_no)+1;
        }else{
          $data['quotation_no'] = 1;
        }
        $data['date'] = date('Y-m-d',strtotime($this->post('quotation_date')));
        $data['customer_name'] = $this->post('customer_name');
        $data['customer_address'] = $this->post('address');
        $data['state'] = $this->post('state');
        $data['expiry_date'] = date('Y-m-d',strtotime($this->post('expiry_date')));
        $data['prepared_by'] = $user_id;
        $data['quotation_type'] = ucwords($this->post('quotation_type'));
        $data['created_date'] = $item_data['created_date'] = date('Y-m-d H:i:s');
        $data['created_by'] = $item_data['created_by'] = $user_id;
        $quotation_update_data['quotation_net_total'] = 0;
        //terms and conditions
        $json_data = $this->post('items');
        $items = json_decode($json_data, true);
        if (!empty($items)) {
          $result = $this->Sales_quotation->insert_quotation($data);
          if($result['status']==1){

            $items_count = sizeof($items);
            $item_data['quotation_id'] = $result['insert_id'];
            for ($i = 0; $i < $items_count; $i++) {
              $item_data['template_id'] = $items[$i]['template_id'];
              $item_data['title'] = $items[$i]['title'];
              $item_data['sub_title'] =$items[$i]['sub_title'];
              $item_data['description'] = $items[$i]['description'];
              $item_data['products'] = $items[$i]['products'];
              $item_data['unit_price'] = $items[$i]['unit_price'];
              $item_data['warranty'] = $items[$i]['warranty'];
              $item_data['method_of_application'] = $items[$i]['method'];
              $item_data['quantity'] = $items[$i]['area'];
              $item_data['total_amount'] = ($items[$i]['area']*$item_data['unit_price']);
              $item_data['notes'] = $items[$i]['notes'];
              $item_result = $this->Sales_quotation->insert_quotation_item($item_data);
              $quotation_update_data['quotation_net_total'] += $item_data['total_amount'];
            }

            $quotation_update_data['quotation_id'] = $result['insert_id'];
            $result = $this->Sales_quotation->update_quotation($quotation_update_data);
          }
          $message = [
            'status' => TRUE,
            'message' => 'Sales Quotation 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['sq.created_by'] = $user_id;
      $sales_quotations = $this->Sales_quotation->select_quotations("sq.*,u.user_alias,u1.user_alias as prepared_by_name,b.*",$data);

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

          $print_url=base_url().'download/sales_quotation?id='.$row->quotation_id."&user=".$user_id."&token=".md5($user_id.$row->quotation_id.$user_id)."&date=".$row->date;
          $item_details = '';
          $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$row->quotation_id))->result();
          foreach ($items as $key => $value) {
            if($this->config->item('Quotation_template')==2){
              $item_details.= $value->title.'['.$value->template_no.'] - '.$value->quantity.' X '.$value->unit_price.' = '.$value->total_amount.'+GST<br/>';
            }else{
              $item_details.= $value->description.' - '.$value->quantity.' X '.$value->unit_price.' = '.$value->total_amount.'<br/>';
            }
          }

          $message[$j]['quotation_id'] = $row->quotation_id;
          $message[$j]['quotation_no'] = '#'.$row->quotation_prefix.'-'.$row->quotation_no.$row->quotation_no_suffix;
          $message[$j]['date'] = date('d-m-Y',strtotime($row->date));
          if($row->expiry_date!='0000-00-00'){
            $message[$j]['expiry_date'] = date('d-m-Y',strtotime($row->expiry_date));
          }else{
            $message[$j]['expiry_date'] = '';
          }
          $message[$j]['customer_name'] = $row->customer_name;
          $message[$j]['customer_address'] = $row->customer_address;
          $message[$j]['quotation_type'] = $row->quotation_type;
          $message[$j]['prepared_by'] = $row->prepared_by_name;
          $message[$j]['quotation_subject'] = $row->quotation_subject;
          $message[$j]['net_total'] = $row->quotation_net_total;
          $message[$j]['created_by'] = $row->user_alias;
          $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
          $message[$j]['approval_status'] = $row->approval_status;
          $message[$j]['item_details'] = $item_details;
          $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('quotation_id')!="" && $this->get('quotation_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['sq.quotation_id'] = $this->get('quotation_id');
      $sales_quotations = $this->Sales_quotation->select_quotations("sq.*,u.user_alias,u1.user_alias as prepared_by_name,b.*",$data);

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

          $message['quotation_id'] = $row->quotation_id;
          $message['quotation_no'] = '#'.$row->quotation_prefix.'-'.$row->quotation_no.$row->quotation_no_suffix;
          $message['date'] = date('d-m-Y',strtotime($row->date));
          if($row->expiry_date!='0000-00-00'){
            $message['expiry_date'] = date('d-m-Y',strtotime($row->expiry_date));
          }else{
            $message['expiry_date'] = '';
          }
          $message['customer_name'] = $row->customer_name;
          $message['customer_address'] = $row->customer_address;
          $message['state'] = $row->state;
          $message['quotation_type'] = $row->quotation_type;
          $message['prepared_by'] = $row->prepared_by_name;
          $message['quotation_subject'] = $row->quotation_subject;
          $message['net_total'] = $row->quotation_net_total;
          $message['created_by'] = $row->user_alias;
          $message['created_date'] = date('d-m-Y',strtotime($row->created_date));
          $message['approval_status'] = $row->approval_status;
          $items_array = array();
          $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$row->quotation_id))->result();
          foreach ($items as $key => $value) {
            $items_array[$j]['item_id'] = $value->item_id;
            $items_array[$j]['template_id'] = $value->template_id;
            $items_array[$j]['title'] = $value->title;
            $items_array[$j]['sub_title'] = $value->sub_title;
            $items_array[$j]['description'] = $value->description;
            $items_array[$j]['products'] = $value->products;
            $items_array[$j]['unit_price'] = $value->unit_price;
            $items_array[$j]['unit_name'] = $value->unit_name;
            $items_array[$j]['warranty'] = $value->warranty;
            $items_array[$j]['quantity'] = $value->quantity;

            $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
    }
  }
}
