<?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_estimation 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_estimation_model','Sales_estimation');
    $this->load->model('Work_order_model','Work_order');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Customers_model','Customers');
    $this->load->model('Branches_model', 'Branches');
    $this->load->model('Material_model', 'Material');
  }
  public function index_get()
  {
    //     Default Method
    $this->select_get();
  }

  public function create_post()
  {
    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;
        $json_data = $this->post('items');
        $items = json_decode($json_data, true);

        $terms_and_conditions = $this->post('terms_and_conditions');
        $terms_and_conditions_array = json_decode($terms_and_conditions, true);
        if (!empty($items)) {
          $data['estimation_to'] = $this->post('estimation_to');
          $data['estimation_date'] = date('Y-m-d',strtotime($this->post('estimation_date')));
          if($data['estimation_to']=='customer'){
            $data['buyer_customer_id'] = $this->post('customer_id');
            $customer_data = $this->Customers->select_customer("",array("customer_id"=>$data['buyer_customer_id']));
            if($customer_data->num_rows()==1){
              $data['buyer_name'] = $customer_data->row()->customer_name;
              $data['buyer_address'] = $customer_data->row()->customer_location;
              $data['buyer_phone'] = $customer_data->row()->customer_phone;
              $data['buyer_taxno'] = $customer_data->row()->customer_tax_no;
              $data['buyer_state_id'] = $customer_data->row()->customer_tax_state;
            }
          }else{
            $data['buyer_branch_id'] = $this->post('branch_id');
            $branch_data	= $this->Branches->select_branches("",array("branch_id"=>$data['buyer_branch_id']));
            if($branch_data->num_rows()==1){
              $data['buyer_name'] = $branch_data->row()->branch_name;
              $data['buyer_address'] = $branch_data->row()->branch_address;
              $data['buyer_phone'] = $branch_data->row()->branch_phone;
              $data['buyer_taxno'] = $branch_data->row()->branch_taxno;
              $data['buyer_state_id'] = $branch_data->row()->tax_state_id;
            }
          }
          // Generate Estimation No
          $estimation_where['se.branch_id'] = $data['branch_id'];
          $estimation_last_data = $this->Sales_estimation->select_sale_estimation("max(se.estimation_no) as max_estimation_no",$estimation_where);
          if($estimation_last_data->num_rows()==1){
            $data['estimation_no'] = ($estimation_last_data->row()->max_estimation_no)+1;
          }else{
            $data['estimation_no'] = 1;
          }

          $data['created_date'] = date('Y-m-d H:i:s');
          $data['created_by'] = $this->post('user_id');

          $terms_new = array();
          for ($i = 0; $i < sizeof($terms_and_conditions_array); $i++) {
            $terms_new[$i]['description'] = $terms_and_conditions_array[$i]['description'];
          }
          if(sizeof($terms_new)>0){
            $data['terms_and_conditions'] = serialize($terms_new);
          }

          $result = $this->Sales_estimation->create_sale_estimation($data);
          if($result['status']==1){
            $items_count = sizeof($items);
            $update_data['net_total'] = $update_data['tax_amount'] = 0;
            for ($i = 0; $i < $items_count; $i++) {
              $material_data = $this->Material->select_material("unit,item_code",array('material_id'=>$items[$i]['material_id']))->row();
              $item_data['material_id'] = $items[$i]['material_id'];
              $item_data['unit_id']  = $material_data->unit;
              $item_data['item_code']  = $material_data->item_code;
              $item_data['quantity'] = $items[$i]['quantity'];
              $item_data['tax_percent'] = $item_data['tax_amount'] = $unit_tax_amount = 0;
              $item_data['unit_sale_price']  = $items[$i]['unit_price'];
              $item_data['tax_percent'] = $items[$i]['tax_percent'];
              $tax_percent = $this->Settings->select_tax_types('*',array("tax_id"=>$item_data['tax_percent']))->row()->tax_percentage;
              $unit_tax_amount = round($item_data['unit_sale_price']*$tax_percent/100,$this->config->item('Currency_amount_decimals_2'));
              $item_data['tax_amount'] = round($unit_tax_amount*$items[$i]['quantity'],$this->config->item('Currency_amount_decimals_2'));
              $update_data['tax_amount'] += $item_data['tax_amount'];
              $item_data['taxable_amount']  = ($item_data['unit_sale_price']*$item_data['quantity']);
              $item_data['total_amount']  = $item_data['taxable_amount']+$item_data['tax_amount'];
              $update_data['net_total'] += $item_data['taxable_amount'];
              $item_data['created_date'] = date('Y-m-d H:i:s');
              $item_data['created_by'] = $this->post('user_id');
              $item_data['estimation_id'] =  $result['insert_id'];
              $result2 = $this->Sales_estimation->create_estimation_items($item_data);
            }

            $update_data['estimation_id'] = $result['insert_id'];
            $update_data['round_amount'] = $this->post('round_amount');
            $update_data['receivable_amount'] = $update_data['net_total'] + $update_data['tax_amount'] - $update_data['round_amount'];
            $this->Sales_estimation->update_sale_estimation($update_data);

            $message = [
              'status' => TRUE,
              'message' => 'Sales Estimation 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 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['se.created_by'] = $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['se.branch_id'] = $employee_data->row()->branch_id;
        $sales_estimations = $this->Sales_estimation->select_sale_estimation("se.*,b.branch_name,u.user_alias,c.customer_id,c.customer_name,b2.branch_name as buyer_branch_name",$data);

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

            $print_url=base_url().'download/sales_estimation?id='.$row->estimation_id."&user=".$user_id."&token=".md5($user_id.$row->estimation_id.$user_id)."&date=".$row->estimation_date;
            $item_details = '';
            $items = $this->Sales_estimation->select_estimation_sale_item("material_name,unit_name,sei.quantity,sei.unit_sale_price,sei.discount_amount,sei.taxable_amount,sei.total_amount,tt.*,sei.description,sei.item_code",array("sei.estimation_id"=>$row->estimation_id))->result();
            foreach ($items as $key => $value) {
              $item_details.= $value->material_name.' - '.$value->quantity.' X '.$value->unit_sale_price.' = '.$value->total_amount.'<br/>';
            }

            $message[$j]['estimation_id'] = $row->estimation_id;
            $message[$j]['estimation_no'] = '#'.$row->estimation_no;
            $message[$j]['date'] = date('d-m-Y',strtotime($row->estimation_date));
            $message[$j]['estimation_to'] = $row->estimation_to;
            if($row->estimation_to=='customer'){
              $message[$j]['buyer_name'] = $row->customer_name;
            }else{
              $message[$j]['buyer_name'] = $row->buyer_branch_name;
            }
            $message[$j]['net_total'] = $row->receivable_amount;
            $message[$j]['created_by'] = $row->user_alias;
            $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
            $message[$j]['item_details'] = $item_details;
            $message[$j]['print_url'] = $print_url;

            $j++;
          endforeach;
        } else {
          $message = [
            'status' => FALSE,
            'message' => 'No Sales Estimations 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' => '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 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('estimation_id')!="" && $this->get('estimation_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['se.estimation_id'] = $this->get('estimation_id');
      $sales_estimations = $this->Sales_estimation->select_sale_estimation("se.*,b.branch_name,u.user_alias,c.customer_id,c.customer_name,b2.branch_name as buyer_branch_name",$data);

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

        $message['estimation_id'] = $row->estimation_id;
        $message['estimation_no'] = '#'.$row->estimation_no;
        $message['date'] = date('d-m-Y',strtotime($row->estimation_date));
        $message['estimation_to'] = $row->estimation_to;
        $message['estimation_to'] = $row->estimation_to;
        $message['buyer_customer_id'] = $row->buyer_customer_id;
        $message['buyer_branch_id'] = $row->buyer_branch_id;
        if($row->estimation_to=='customer'){
          $message['buyer_name'] = $row->customer_name;
        }else{
          $message['buyer_name'] = $row->buyer_branch_name;
        }
        $message['net_total'] = $row->receivable_amount;
        $message['created_by'] = $row->user_alias;
        $message['created_date'] = date('d-m-Y',strtotime($row->created_date));

        $items_array = array();
        $items = $this->Sales_estimation->select_estimation_sale_item("",array("sei.estimation_id"=>$row->estimation_id))->result();
        foreach ($items as $key => $value) {
          $items_array[$j]['item_id'] = $value->item_id;
          $items_array[$j]['material_id'] = $value->material_id;
          $items_array[$j]['unit_price'] = $value->unit_sale_price;
          $items_array[$j]['unit_name'] = $value->unit_name;
          $items_array[$j]['quantity'] = $value->quantity;
          $items_array[$j]['tax_percent'] = $value->tax_percent;
          $items_array[$j]['total_amount'] = $value->total_amount;

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

      } else {
        $message = [
          'status' => FALSE,
          'message' => 'Sales Estimation 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, Estimation ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
}
