<?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 Data 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('Branches_model', 'Branches');
    $this->load->model('Customers_model','Customers');
    $this->load->model('Services_model','Services');
    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $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->model('Tools_model', 'Tools');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Travel_allowance_model', 'Travel_allowance');
    $this->load->library('Projects_management','projects_management');
  }
  public function index_get()
  {
    //     Default Method
    $this->select_dropdowns_get();
  }
  //  Account Heads, Payment Modes, Expense Heads
  public function select_dropdowns_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      if($user_details->num_rows()==1){
        $account_heads_where = $expense_heads_where = $projects_where = array();
        $sale_price_categories = $services = $tax_state_codes = $customers = $bank_accounts = $vehicle_document_types = $supervisors = $contractors = $tax_percentages = $account_heads = $expense_heads = $payment_modes = $projects = $labours = $work_types = $tool_categories = $measure_units =  array();
        // Account Heads
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['e.user_id'] = $this->get('user_id');
        $account_heads_data	= $this->Account->select_account_heads("",$account_heads_where,'user');
        if ($account_heads_data->num_rows() > 0) {
          $j = 0;
          foreach ($account_heads_data->result() as $row):
            $account_heads[$j]['head_id'] = $row->acc_head_id;
            $account_heads[$j]['head_name'] = $row->acc_head_name;
            $j++;
          endforeach;
        }
        // Expense Heads
        $expense_heads_where['ah.delete_status'] = 0;
        $this->db->where('ah.account_type=11');
        $expense_heads_data	= $this->Account->select_account_heads("",$expense_heads_where);
        if ($expense_heads_data->num_rows() > 0) {
          $j = 0;
          foreach ($expense_heads_data->result() as $row):
            $expense_heads[$j]['head_id'] = $row->acc_head_id;
            $expense_heads[$j]['head_name'] = $row->acc_head_name;
            $j++;
          endforeach;
        }
        // Payment Modes
        $payment_modes_data	= unserialize($this->Settings->select_settings("value",array("settings_name"=>'payment_modes'))->row()->value);
        if (sizeof($payment_modes_data) > 0) {
          $j = 0;
          foreach ($payment_modes_data as $row):
            $payment_modes[$j]['id'] = $row;
            $payment_modes[$j]['name'] = $row;
            $j++;
          endforeach;
        }
        // Tax %
        $tax_percentages_new	= $this->config->item('Tax_tax_percent');
        $tax_percentages = $this->config->item('Tax_tax_percent_old');

        //    Select Assigned Works Only
        $user_id = $this->get('user_id');
        if($user_details->row()->role_name=='supervisor'){
          $this->db->where("FIND_IN_SET($user_id, w.assigned_users)");
        }
        $projects_where['w.delete_status'] = 0;
        if($this->get('work_id')){
          $projects_where['work_id'] = $this->get('work_id');
        }
        $projects_data	= $this->Work->select_work("w.work_id,w.work_name",$projects_where);
        if ($projects_data->num_rows() > 0) {
          $j = 0;
          foreach ($projects_data->result() as $row):
            $projects[$j]['work_id'] = $row->work_id;
            $projects[$j]['work_name'] = $row->work_name;
            $j++;
          endforeach;
        }
        // Select Labours
        if($this->get('work_id') && $this->get('work_id')!='' && $this->config->item('Labour_projet_assigning')==1){
          $work_id = $this->get('work_id');
          $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
        }
        $labours_data	= $this->Labour->select_labours("l.*,wt.type_name,u.user_alias");
        if ($labours_data->num_rows() > 0) {
          $j = 0;
          foreach ($labours_data->result() as $row):
            $opening_balance  = $row->opening_balance;
            $total_to_pay = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("lw.labour_id"=>$row->labour_id))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
            $payment_data['l.labour_id'] = $row->labour_id;
            $payment_data['ats.tr_type'] = 'labour_transaction';
            $payment_data['ats.reference_type'] = 'labour';
            $total_paid = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
            $current_balance_group = 0;
            if($row->labour_type==0){
              $labour_type = "Individual";
            }else{
              if($row->group_position==1){
                $labour_type = "Group Leader";

                // $json_data['opening_balance_group'] = round($this->Labour->select_labours("COALESCE(SUM(l.opening_balance),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total,$this->config->item('Currency_amount_decimals_2'));
                // $json_data['total_work_days_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total,$this->config->item('Currency_amount_decimals_2'));
                // $json_data['total_wage_earned_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("l.labour_group"=>$row->labour_group))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
                // $json_data['total_to_pay_group'] = round(($json_data['total_wage_earned_group'] + $json_data['opening_balance_group']),$this->config->item('Currency_amount_decimals_2'));

                $payment_data_2['l.labour_group'] = $row->labour_group;
                $payment_data_2['ats.tr_type'] = 'labour_transaction';
                $payment_data_2['ats.reference_type'] = 'labour';
                // $json_data['total_paid_group'] = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data_2,'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
                // $current_balance_group  = $json_data['total_to_pay_group']-$json_data['total_paid_group'];
              }else{
                $labour_type = "Group Member";
              }
            }
            $labours[$j]['labour_id'] = $row->labour_id;
            $labours[$j]['labour_name'] = $row->labour_name. " [".$labour_type."]";
            $labours[$j]['work_type'] = $row->type_name;
            $labours[$j]['fixed_wage_status'] = $row->fixed_wage;
            $labours[$j]['daily_wage'] = (float)$row->daily_wage;
            $labours[$j]['overtime_rate'] = (float)$row->overtime_rate_per_hr;
            $labours[$j]['work_type'] = $row->type_name;
            $labours[$j]['labour_type'] = $row->labour_type;
            $labours[$j]['group_position'] = $row->group_position;
            $labours[$j]['current_balance_personal']  = (float)round(($total_to_pay+$opening_balance-$total_paid),$this->config->item('Currency_amount_decimals_2'));
            $labours[$j]['current_balance_group']  = (float)round($current_balance_group,$this->config->item('Currency_amount_decimals_2'));
            if($row->photo!=''){
              $photo = base_url().'uploads/labours/'.$row->photo;
            }else{
              $photo = base_url().'uploads/labours/default.png';
            }
            $labours[$j]['photo'] = $photo;
            $j++;
          endforeach;
        }
        // Select WorkType
        $work_types_data	= $this->Work->select_work_types("");
        if ($work_types_data->num_rows() > 0) {
          $j = 0;
          foreach ($work_types_data->result() as $row):
            $work_types[$j]['type_id'] = $row->type_id;
            $work_types[$j]['type_name'] = $row->type_name;
            $j++;
          endforeach;
        }
        // Select Tool Categories
        $tool_categories_data	= $this->Tools->select_tools_category("");
        if ($tool_categories_data->num_rows() > 0) {
          $j = 0;
          foreach ($tool_categories_data->result() as $row):
            $tool_categories[$j]['cat_id'] = $row->cat_id;
            $tool_categories[$j]['cat_name'] = $row->cat_name;
            $j++;
          endforeach;
        }

        // Select Measure Units
        $measure_units_data	= $this->Material->select_unit();
        if ($measure_units_data->num_rows() > 0) {
          $j = 0;
          foreach ($measure_units_data->result() as $row):
            $measure_units[$j]['unit_id'] = $row->unit_id;
            $measure_units[$j]['unit_name'] = $row->unit_name;
            $j++;
          endforeach;
        }

        $contractors_data	= $this->Subcontracts->select_contractors("");
        if ($contractors_data->num_rows() > 0) {
          $j = 0;
          foreach ($contractors_data->result() as $row):
            $contractors[$j]['contractor_id'] = $row->contractor_id;
            $contractors[$j]['contractor_name'] = $row->contractor_name;
            $contractors[$j]['phone'] = $row->phone;
            $j++;
          endforeach;
        }

        $supervisors_data = $this->User->select_user("",array("role_name"=>'supervisor'));
        if ($supervisors_data->num_rows() > 0) {
          $j = 0;
          foreach ($supervisors_data->result() as $row):
            $supervisors[$j]['user_id'] = $row->user_id;
            $supervisors[$j]['user_alias'] = $row->user_alias;
            $j++;
          endforeach;
        }
        $bank_accounts = $this->Settings->select_bank_account_details()->result_array();
        $services = $this->Services->select_services("",array('active_status'=>1))->result_array();
        $tax_state_codes = $this->Settings->select_tax_state_codes("*")->result_array();
        $customers = $this->Customers->select_customer("*")->result_array();
        $sale_price_categories[0]['value'] = 1;
        $sale_price_categories[0]['name'] = $this->config->item('Material_sale_price1_name');
        $sale_price_categories[1]['value'] = 2;
        $sale_price_categories[1]['name'] = $this->config->item('Material_sale_price2_name');
        $sale_price_categories[2]['value'] = 3;
        $sale_price_categories[2]['name'] = $this->config->item('Material_sale_price3_name');
        $sale_price_categories[3]['value'] = 4;
        $sale_price_categories[3]['name'] = $this->config->item('Material_sale_price4_name');
        $sale_price_categories[4]['value'] = 5;
        $sale_price_categories[4]['name'] = $this->config->item('Material_sale_price5_name');
        $sale_price_categories[5]['value'] = 6;
        $sale_price_categories[5]['name'] = $this->config->item('Material_sale_price6_name');


        $ta_vehicles = $this->Travel_allowance->select_ta_vehicles()->result_array();
        $vehicle_document_types = $this->Vehicle->select_vehicle_document_types()->result_array();
        if (sizeof($sale_price_categories) == 0 && sizeof($services) == 0 && sizeof($tax_state_codes) == 0 && sizeof($customers) == 0 && sizeof($bank_accounts) == 0 && sizeof($supervisors) == 0 && sizeof($vehicle_document_types) == 0 && sizeof($tax_percentages) == 0 && sizeof($ta_vehicles) == 0 && sizeof($measure_units) == 0 && sizeof($account_heads) == 0 && sizeof($expense_heads) == 0 && sizeof($payment_modes) == 0 && sizeof($projects) == 0 && sizeof($labours) == 0 && sizeof($work_types) == 0 && sizeof($tool_categories) == 0) {
          $message = [
            'status' => FALSE,
            'message' => 'No Datas Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }else {
          $json_data['status'] = TRUE;
          $json_data['account_heads'] = $account_heads;
          $json_data['expense_heads'] = $expense_heads;
          $json_data['payment_modes'] = $payment_modes;
          $json_data['projects'] = $projects;
          $json_data['labours'] = $labours;
          $json_data['work_types'] = $work_types;
          $json_data['measure_units'] = $measure_units;
          $json_data['tool_categories'] = $tool_categories;
          $json_data['tax_percentages_new'] = $tax_percentages_new;
          $json_data['tax_percentages'] = explode(',',implode(',',$tax_percentages));
          $json_data['ta_vehicle_type'] = $ta_vehicles;
          $json_data['contractors'] = $contractors;
          $json_data['vehicle_document_types'] = $vehicle_document_types;
          $json_data['supervisors'] = $supervisors;
          $json_data['bank_accounts'] = $bank_accounts;
          $json_data['services'] = $services;
          $json_data['tax_state_codes'] = $tax_state_codes;
          $json_data['customers'] = $customers;
          $json_data['sale_price_categories'] = $sale_price_categories;
          $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'User 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 Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_labours_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      if($user_details->num_rows()==1){
        $data = array();
        // Select Labours
        if($this->get('list_type') && $this->get('list_type')=='team_leader'){
          $data['l.labour_type'] = 1;
          $data['l.group_position'] = 1;
        }
        if($this->get('labour_group') && $this->get('labour_group')=='team_member'){
          $data['l.labour_type'] = 1;
          $data['l.group_position'] = 0;
        }
        if($this->get('labour_group') && $this->get('labour_group')!=''){
          $data['l.labour_group'] = $this->get('labour_group');
        }
        if($this->get('work_id') && $this->get('work_id')!='' && $this->config->item('Labour_projet_assigning')==1){
          $work_id = $this->get('work_id');
          $this->db->where("FIND_IN_SET($work_id, l.assigned_projects)");
        }
        $labours_data	= $this->Labour->select_labours("l.*,wt.type_name,u.user_alias",$data);
        if ($labours_data->num_rows() > 0) {
          $j = 0;
          foreach ($labours_data->result() as $row):
            $opening_balance  = $row->opening_balance;
            $total_to_pay = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("lw.labour_id"=>$row->labour_id))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
            $payment_data['l.labour_id'] = $row->labour_id;
            $payment_data['ats.tr_type'] = 'labour_transaction';
            $payment_data['ats.reference_type'] = 'labour';
            $total_paid = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
            $current_balance_group = 0;
            if($row->labour_type==0){
              $labour_type = "Individual";
            }else{
              if($row->group_position==1){
                $labour_type = "Group Leader";

                $json_data['opening_balance_group'] = round($this->Labour->select_labours("COALESCE(SUM(l.opening_balance),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total,$this->config->item('Currency_amount_decimals_2'));
                $json_data['total_work_days_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.work_days),0) as total",array("l.labour_group"=>$row->labour_group))->row()->total,$this->config->item('Currency_amount_decimals_2'));
                $json_data['total_wage_earned_group'] = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total_amount",array("l.labour_group"=>$row->labour_group))->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
                $json_data['total_to_pay_group'] = round(($json_data['total_wage_earned_group'] + $json_data['opening_balance_group']),$this->config->item('Currency_amount_decimals_2'));

                $payment_data_2['l.labour_group'] = $row->labour_group;
                $payment_data_2['ats.tr_type'] = 'labour_transaction';
                $payment_data_2['ats.reference_type'] = 'labour';
                $json_data['total_paid_group'] = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data_2,'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));
                $current_balance_group  = $json_data['total_to_pay_group']-$json_data['total_paid_group'];
              }else{
                $labour_type = "Group Member";
              }
            }

            $labours[$j]['labour_id'] = $row->labour_id;
            $labours[$j]['labour_name'] = $row->labour_name. " [".$labour_type."]";
            $labours[$j]['labour_group'] = $row->labour_group;
            $labours[$j]['work_type'] = $row->type_name;
            $labours[$j]['fixed_wage_status'] = $row->fixed_wage;
            $labours[$j]['daily_wage'] = $row->daily_wage;
            $labours[$j]['overtime_rate'] = (float)$row->overtime_rate_per_hr;
            $labours[$j]['work_type'] = $row->type_name;
            $labours[$j]['labour_type'] = $row->labour_type;
            $labours[$j]['group_position'] = $row->group_position;
            $labours[$j]['current_balance_personal']  = round(($total_to_pay+$opening_balance-$total_paid),$this->config->item('Currency_amount_decimals_2'));
            $labours[$j]['current_balance_group']  = round($current_balance_group,$this->config->item('Currency_amount_decimals_2'));
            if($row->photo!=''){
              $photo = base_url().'uploads/labours/'.$row->photo;
            }else{
              $photo = base_url().'uploads/labours/default.png';
            }
            $labours[$j]['photo'] = $photo;
            $j++;
          endforeach;
        }

        if (sizeof($labours) == 0) {
          $message = [
            'status' => FALSE,
            'message' => 'No Labours Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }else {
          $json_data['labours'] = $labours;
          $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'User 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 Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }

  public function select_sales_dropdowns_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {
      $json_data['branches'] = $json_data['customers'] = $json_data['sale_price_category'] = $json_data['terms_and_conditions'] = array();

      $user_details = $this->User->select_user("",array("user_id"=>$this->get('user_id')));
      if($user_details->num_rows()==1){

        for($i=0;$i<6;$i++){
          $json_data['sale_price_category'][$i]['id'] = $i+1;
          $json_data['sale_price_category'][$i]['name'] = $this->config->item('Material_sale_price'.($i+1).'_name');
        }

        if($user_details->row()->branch_id==0){
          $branches	= $this->Branches->select_branches("");
          if ($branches->num_rows() > 0) {
            $json_data['branches'] = $branches->result_array();
          }
        }

        $customers_where['c.branch_id'] = $user_details->row()->branch_id;
        $customers	= $this->Customers->select_customer("",$customers_where);
        if ($customers->num_rows() > 0) {
          $json_data['customers'] = $customers->result_array();
        }

        $json_data['terms_and_conditions'] = $this->Settings->select_terms_and_condition_templates('',array("terms_type"=>'Sales Estimation'))->result_array();

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

}
