<?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 Subcontracts 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('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Labour_wages_model', 'Labour_wages');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Bills_model', 'Bills');
    $this->load->library('Bills_management','bills_management');
    $this->load->library('Projects_management','projects_management');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $this->load->model('Daily_reports_model', 'Daily_reports');
  }
  public function index_get()
  {
    //     Default Method
    $this->select_get();
  }

  public function create_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('work_id')!="" && $this->post('work_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->post('user_id')));

      $data['work_id'] = $this->post('work_id');
      $project_details = $this->Work->select_work("work_name",array("work_id"=>$data['work_id']));

      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->post('user_id');
      $data['sub_work_name'] = $this->post('work_name');
      $data['contractor'] = $this->post('contractor');
      $data['contract_type'] = $this->post('contract_type');
      $data['description'] = $this->post('description');
      $data['project_stage_id'] = $this->projects_management->get_project_stage_id($data['work_id']);
      if($this->config->item('Mobile_App_subcontract_entry_approval')==1){
        $data['contract_approval_status'] = 0;
      }
      $result =  $this->Subcontracts->create_subcontract($data);

      if($result['status']==1){
        $item_data['subcontract_id'] = $subcontract_data['contract_id'] = $result['insert_id'];
        $item_data['created_date'] = date('Y-m-d H:i:s');
        $item_data['created_by'] = $this->post('user_id');

        $subcontract_data['work_type_id']="";
        $subcontract_data['total_budget']=0;
        $subcontract_data['op_balance']= $this->post('op_balance');
        $work_types = array();

        $json_data = $this->post('items');
        $items = json_decode($json_data, true);
        if (!empty($items)) {
          $items_count = sizeof($items);
          for ($i = 0; $i < $items_count; $i++) {
            $item_data['work_type'] = $items[$i]['work_type'];
            $work_types[] =  $items[$i]['work_type'];
            if($data['contract_type']=='unit_rate'){
              $item_data['measure_unit'] = $items[$i]['unit'];
              $item_data['unit_rate'] = $items[$i]['unit_rate'];
              $item_data['qty'] = $items[$i]['quantity'];
            }else{
              unset($item_data['measure_unit']);
              unset($item_data['unit_rate']);
              unset($item_data['qty']);
            }
            $item_data['est_amount'] = $items[$i]['est_amount'];

            $subcontract_data['total_budget']+=$items[$i]['est_amount'];
            $item_data['remarks'] = $items[$i]['remarks'];
            $item_result =  $this->Subcontracts->create_subcontract_work_item($item_data);

          }

          // Update Subcontract
          $subcontract_data['work_type_id'] = implode(",",$work_types);
          $result_2 =  $this->Subcontracts->update_subcontract($subcontract_data);

          $message = [
            'status' => TRUE,
            'message' => 'Subcontract Added Successfully'
          ];
          $this->response($message, REST_Controller::HTTP_CREATED); // 201
        }else{
          $message = [
            'status' => FALSE,
            'message' => 'No Items Uploaded'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'There Has been Some Error Occurred'
        ];
        $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, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function update_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('work_id')!="" && $this->post('work_id') !== NULL && $this->post('contract_id')!="" && $this->post('contract_id') !== NULL ) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->post('user_id')));

      $data['work_id'] = $this->post('work_id');
      $project_details = $this->Work->select_work("work_name",array("work_id"=>$data['work_id']));

      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->post('user_id');
      $data['sub_work_name'] = $this->post('work_name');
      $data['contractor'] = $this->post('contractor');
      $data['contract_type'] = $this->post('contract_type');
      $data['description'] = $this->post('description');
      $result =  $this->Subcontracts->create_subcontract($data);

      if($result['status']==1){
        $item_data['subcontract_id'] = $subcontract_data['contract_id'] = $result['insert_id'];
        $item_data['created_date'] = date('Y-m-d H:i:s');
        $item_data['created_by'] = $this->post('user_id');

        $subcontract_data['work_type_id']="";
        $subcontract_data['total_budget']=0;
        $subcontract_data['op_balance']= $this->post('op_balance');
        $work_types = array();

        $json_data = $this->post('items');
        $items = json_decode($json_data, true);
        if (!empty($items)) {
          $items_count = sizeof($items);
          for ($i = 0; $i < $items_count; $i++) {
            $item_data['work_type'] = $items[$i]['work_type'];
            $work_types[] =  $items[$i]['work_type'];
            if($data['contract_type']=='unit_rate'){
              $item_data['measure_unit'] = $items[$i]['unit'];
              $item_data['unit_rate'] = $items[$i]['unit_rate'];
              $item_data['qty'] = $items[$i]['quantity'];
            }else{
              unset($item_data['measure_unit']);
              unset($item_data['unit_rate']);
              unset($item_data['qty']);
            }
            $item_data['est_amount'] = $items[$i]['est_amount'];

            $subcontract_data['total_budget']+=$items[$i]['est_amount'];
            $item_data['remarks'] = $items[$i]['remarks'];
            $item_result =  $this->Subcontracts->create_subcontract_work_item($item_data);

          }

          // Update Subcontract
          $subcontract_data['work_type_id'] = implode(",",$work_types);
          $result_2 =  $this->Subcontracts->update_subcontract($subcontract_data);

          $message = [
            'status' => TRUE,
            'message' => 'Subcontract Added Successfully'
          ];
          $this->response($message, REST_Controller::HTTP_CREATED); // 201
        }else{
          $message = [
            'status' => FALSE,
            'message' => 'No Items Uploaded'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'There Has been Some Error Occurred'
        ];
        $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, Work ID,Contract 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 && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $data=array();

      $user_id = $this->get('user_id');
      $data['wc.work_id'] = $this->get('work_id');
      $subcontracts	= $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*",$data);
      if ($subcontracts->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($subcontracts->result() as $row):
          $work_types = array();
          if($row->work_type_names!=''){
            $work_types = explode(",",$row->work_type_names);
          }

          $no_of_bills=$this->Bills->select_bills("b.bill_id",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->num_rows();
          $bill_amount=$this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;
          $bill_paid_amount=$this->Bills->select_bills("COALESCE(SUM(bill_total_paid),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;
          $advance_paid_amount=$this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $row->contract_id, "ats.reference_type" => 'subcontract'),'subcontract_advance')->row()->total_paid_amount;
          $bill_balance_amount=$this->Bills->select_bills("COALESCE(SUM(bill_balance_amount),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;

          if($row->contract_approval_status==1){
            $subcontract_approval_status='Approved';
          }elseif($row->contract_approval_status==2){
            $subcontract_approval_status='Rejected';
          }else{
            $subcontract_approval_status='Pending';
          }

          $message[$j]['contract_id'] = $row->contract_id;
          $message[$j]['sub_work_name'] = $row->sub_work_name;
          $message[$j]['date'] = ($row->subcontract_date!='0000-00-00')?date('d-m-Y',strtotime($row->subcontract_date)):"";
          $message[$j]['work_type_names'] = $work_types;
          $message[$j]['contractor'] = $row->contractor_name;
          $message[$j]['description'] = $row->description;
          $message[$j]['contract_type'] = ucwords(str_replace('_','_',$row->contract_type));
          $message[$j]['op_balance']=$row->op_balance;
          $message[$j]['total_budget']=$row->total_budget;
          $message[$j]['no_of_bills'] = $no_of_bills;
          $message[$j]['bill_amount'] = $bill_amount;
          $message[$j]['bill_amount'] = $bill_amount;
          $message[$j]['bill_paid_amount'] = $bill_paid_amount;
          $message[$j]['advance_paid_amount'] = $advance_paid_amount;
          $message[$j]['bill_balance_amount'] = $bill_balance_amount;
          $message[$j]['contract_approval_status_flag'] = $row->contract_approval_status;
          $message[$j]['contract_approval_status'] = $subcontract_approval_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' => 'No Subcontracts Found For This Project'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work 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('work_id')!="" && $this->get('work_id') !== NULL && $this->get('contract_id')!="" && $this->get('contract_id') !== NULL ) {

      $data=array();

      $user_id = $this->get('user_id');
      $data['sc.contract_id'] = $this->get('contract_id');
      $subcontracts	= $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.contractor_name",$data);
      if ($subcontracts->num_rows()==1) {
        $row = $subcontracts->row();
        $message = array();
        $j = 0;

        $work_types = explode(",",$row->work_type_names);

        $no_of_bills=$this->Bills->select_bills("b.bill_id",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->num_rows();
        $bill_amount=$this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;
        $bill_paid_amount=$this->Bills->select_bills("COALESCE(SUM(bill_total_paid),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;
        $advance_paid_amount=$this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $row->contract_id, "ats.reference_type" => 'subcontract'),'subcontract_advance')->row()->total_paid_amount;
        $bill_balance_amount=$this->Bills->select_bills("COALESCE(SUM(bill_balance_amount),0) as total_amount",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;


        $bills_where['b.created_by'] = $user_id;
        $bills_where['b.subcontract_id'] = $row->contract_id;
        $bills_where['b.bill_type'] = 'subcontract';
        $bills_data = $this->Bills->select_bills("b.*,DATE_FORMAT(b.created_date,'%d-%m-%Y') AS created_date",$bills_where,'','','',$this->config->item('select_data_entry_approval'))->result_array();

        $sub_contract_payment_where['ats.created_by'] = $user_id;
        $this->db->where("((sc.contract_id=".$row->contract_id." and ats.tr_type='subcontract_bill_transaction') or (sc2.contract_id=".$row->contract_id." and  ats.tr_type='subcontract_advance_transaction'))");
        $this->db->where("((ats.reference_type='subcontract_bill' or ats.reference_type='subcontract'))");
        $sub_contract_payments = $this->Account->select_account_transaction("ats.*,DATE_FORMAT(ats.created_date,'%d-%m-%Y') AS created_date,ats.tr_entry_approval_status as entry_approval_status,b.bill_id,b.bill_no,b.bill_date", $sub_contract_payment_where,'subcontract_transactions','','','',$this->config->item('select_data_entry_approval'))->result_array();

        $message['contract_id'] = $row->contract_id;
        $message['sub_work_name'] = $row->sub_work_name;
        $message['work_type_names'] = $work_types;
        $message['contractor'] = $row->contractor_name;
        $message['description'] = $row->description;
        $message['contract_type'] = ucwords(str_replace('_','_',$row->contract_type));
        $message['op_balance']=$row->op_balance;
        $message['total_budget']=$row->total_budget;
        $message['no_of_bills'] = $no_of_bills;
        $message['bill_amount'] = $bill_amount;
        $message['bill_amount'] = $bill_amount;
        $message['bill_paid_amount'] = $bill_paid_amount;
        $message['advance_paid_amount'] = $advance_paid_amount;
        $message['bill_balance_amount'] = $bill_balance_amount;
        $message['work_type_id'] = $row->work_type_id;
        $message['work_id'] = $row->work_id;
        $message['bills'] = $bills_data;
        $message['payments'] = $sub_contract_payments;
        $message['contract_approval_status'] = $row->contract_approval_status;

        $message['status'] = TRUE;
        $this->set_response($message, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'Subcontracts Details Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID,Contract ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  // Subcontract Activities
  public function select_activities_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL && $this->get('work_id')!="" && $this->get('work_id') !== NULL) {

      $data=array();
      //          Select Assigned Tasks Only
      $user_id = $this->get('user_id');
      $data['dr.created_by'] = $user_id;
      $data['dr.report_type'] = 'subcontract';
      if($this->get('work_id')){
        $data['dr.work_id'] = $this->get('work_id');
      }
      if($this->get('contract_id')){
        $data['dr.subcontract_id'] = $this->get('contract_id');
      }
      $subcontract_report	= $this->Daily_reports->select_labour_report("dr.*,sc.contractor,sc.sub_work_name,wt2.type_name,u.user_alias as created_user,wc.work_id,wc.work_name",$data);
      if ($subcontract_report->num_rows() > 0) {
        $message = array();
        $j = 0;
        foreach ($subcontract_report->result() as $row):

          $message[$j]['report_id'] = $row->report_id;
          $message[$j]['work_name'] = $row->work_name;
          $message[$j]['contractor'] = $row->contractor;
          $message[$j]['work_type'] = $row->type_name;
          $message[$j]['sub_work_name'] = $row->sub_work_name;
          $message[$j]['date'] = date('d-m-Y',strtotime($row->report_date));
          $message[$j]['title'] = $row->title;
          $message[$j]['description'] = $row->description;
          $message[$j]['created_by'] = $row->created_user;
          $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));

          $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' => 'No Subcontract Activites Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID, Work ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function create_activity_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('work_id')!="" && $this->post('work_id') !== NULL && $this->post('contract_id')!="" && $this->post('contract_id') !== NULL) {

      $data['work_id'] = $this->post('work_id');
      $data['report_date'] = date('Y-m-d');
      $data['title'] = $this->post('title');
      $data['description'] = $this->post('description');
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->post('user_id');
      $data['report_type'] = 'subcontract';
      $data['subcontract_id'] = $this->post('contract_id');
      $result =  $this->Daily_reports->create_labour_report($data);
      if($result['status'] == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Subcontract Report Submitted Successfully'
        ];
        $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
      }else {
        $message = [
          'status' => FALSE,
          'message' => 'There Has Been Some Error Occurred'
        ];
        $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, Work ID,Contract ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function update_activity_post()
  {
    if($this->post('user_id')!="" && $this->post('user_id') !== NULL && $this->post('work_id')!="" && $this->post('work_id') !== NULL && $this->post('report_id')!="" && $this->post('report_id') !== NULL) {

      $data['report_id'] = $this->post('report_id');
      $data['title'] = $this->post('title');
      $data['description'] = $this->post('description');
      $data['updated_date'] = date('Y-m-d H:i:s');
      $data['updated_by'] = $this->post('user_id');

      $result =  $this->Daily_reports->update_labour_report($data);
      if($result == 1) {
        $message = [
          'status' => TRUE,
          'message' => 'Subcontract Report Updated Successfully'
        ];
        $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
      }else {
        $message = [
          'status' => FALSE,
          'message' => 'There Has Been Some Error Occurred'
        ];
        $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, Work ID, Report ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
}
