<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Payment_Schedule extends CI_Controller
{
  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    $this->initial();
  }
  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Payment_schedule_model', 'payment_schedule');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","accounts_manager","auditor","procurement_engineer","project_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "clients";

  }
  public function index()
  {
    // $this->view();
  }

  public function create()
  {

    $data['type'] = $this->security->xss_clean($this->input->post('type'));
    $data['reference_id'] = $this->security->xss_clean($this->input->post('reference_id'));
    $data['scheduled_amount'] = $this->security->xss_clean($this->input->post('scheduled_amount'));
    $data['scheduled_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('scheduled_date'))));
    $data['stage_no'] = $this->security->xss_clean($this->input->post('stage_no'));
    $data['stage_name'] = $this->security->xss_clean($this->input->post('stage_name'));
    $data['remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $data['reference_type'] = $this->security->xss_clean($this->input->post('reference_type'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');

    $result =  $this->payment_schedule->create_schedule($data);
    $json_data['status'] = $result['status'];
    if ($json_data['status'] == 1) {
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = "Payment Schedule Created Successfully";
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = "Payment Schedule Creation failed !";
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Success !';
    }
    echo json_encode($flash_data);
  }


  public function select_schedule_payments(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=0;
    $data=array();

    $type = $this->security->xss_clean($this->input->post('type'));
    if(isset($type) && $type!=''){
      $data['ps.type'] = $type;
    }
    $reference = $this->security->xss_clean($this->input->post('reference'));
    if(isset($reference) && $reference!='' && $reference!='all'){
      if(isset($type) && $type=='subcontract_payment'){
        $data['wc.work_id'] = $reference;
      }else{
        $data['ps.reference_id'] = $reference;
        $clients = $this->security->xss_clean($this->input->post('clients'));
        if(isset($clients) && $clients!='' && $clients!='all'){
          $data['wc.client_id'] = $clients;
        }
      }
    }

    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(ps.scheduled_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(ps.scheduled_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['ps.scheduled_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['ps.scheduled_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['contractor']) && $_POST['contractor']!='' && $_POST['contractor']!='all'){
      $data['s.contractor'] = $_POST['contractor'];
    }



    if($this->session->userdata('user_role') != 'auditor' && $this->session->userdata('user_role')!='admin' && $this->session->userdata('user_role')!='general_manager' && $this->session->userdata('user_role')!='accounts_manager' && $this->session->userdata('user_role')!='project_manager'){
      // if($this->session->userdata('user_role')!='general_manager' || ($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_data_access_view_all')==0)){
      //   $data['ps.created_by'] = $this->session->userdata('user_id');
      // }
      // if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
      // $data['ps.created_by'] = $this->session->userdata('user_id');
      // }

      if($this->session->userdata('user_role')=='supervisor') {
        //          Select Assigned Works Only
        $supervisor_id = $this->session->userdata('user_id');
        $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
      }else{
        $data['ps.created_by'] = $this->session->userdata('user_id');
      }
    }
    // if(isset($_POST['created_by']) && $_POST['created_by']!='' && $_POST['created_by']!='all'){
    //   $this->db->where("ps.created_by",$_POST['created_by']);
    // }
    // if(isset($_POST['start_month']) && $_POST['start_month']!='' && $_POST['start_month']!='all'){
    //   $start_date=date('Y-m-d', strtotime("01-".$_POST['start_month']));
    //   $this->db->where("ats.tr_date >=",$start_date);
    // }
    // if(isset($_POST['end_month']) && $_POST['end_month']!='' && $_POST['end_month']!='all'){
    //   $end_date=date('Y-m-t', strtotime("01-".$_POST['end_month']));
    //   $this->db->where("ats.tr_date <=",$end_date);
    // }
    // $data['ats.tr_type'] = 'client_payment_transaction';
    // $data['ats.reference_type'] = 'project';

    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['wc.branch_id'] = $_POST['branch_id'];
    }

    $join = $select_columns = '';
    if(isset($type) && $type=='client_payment'){
      $join = 'work';
      $select_columns = ',wc.work_name as work,wc.work_id as work_id,c.client_name as client_name';
    }
    if(isset($type) && $type=='subcontract_payment'){
      $join = 'subcontract';
      $select_columns = ',c.contractor_name,s.sub_work_name,s.contract_id,s.contractor,wc.work_id,wc.work_name as work,wc.work_id as work_id';
    }
    $result = $this->payment_schedule->select_schedule("ps.*,u.user_alias as created_user".$select_columns,$data,$join);
    $result_array=$result->result();
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();

    foreach($result_array as $row):
      $transaction_id_column = 1;
      if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_id')==$row->created_by)) {
        // $btn_send='<a style="margin-left: 5px;margin-right: 5px" id="send_email_btn" href="#send_email_modal" data-toggle="modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        // <i class="la la-envelope"></i>
        // </a>';
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="payment_schedule_edit_btn" href="#payment_schedule_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="btn_delete_payment_schedule"  href="#payment_schedule_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }else{
        $btn_edit = '';
        $btn_delete='';
      }
      $payment_type = "<span style='margin-top: 5px' class='m-badge m-badge--info m-badge--wide'>". strtoupper(str_replace('_', ' ', $row->type))."</span>";
      $work_name = $work_id = $sub_work_name = '';
      if(isset($row->work)){
        $work_name = $row->work;
      }
      if(isset($row->work_id)){
        $work_id = $row->work_id;
      }
      if(isset($row->sub_work_name)){
        $sub_work_name = $row->sub_work_name;
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = $payment_type;
      $array[$j][] = $work_name;
      if(isset($type) && $type=='client_payment'){
        $array[$j][] = $row->client_name;
      }
      if(isset($type) && $type=='subcontract_payment'){
        $array[$j][] = $sub_work_name;
        $array[$j][] = $row->contractor_name;
      }
      $array[$j][] = $row->stage_no;
      $array[$j][] = $row->stage_name;
      $array[$j][] = date('d-m-Y',strtotime($row->scheduled_date));
      $array[$j][] = $row->scheduled_amount;
      $array[$j][] = $row->remarks;
      $array[$j][]=$row->created_user;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][] = $row->schedule_id;
      $array[$j][] = $work_id;
      if(isset($type) && $type=='subcontract_payment'){
        $array[$j][] = $row->contract_id;
      }

      $total_amount=$total_amount+$row->scheduled_amount;

      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      if(isset($type) && $type=='client_payment'){
        $array[$j][]='';
      }
      if(isset($type) && $type=='subcontract_payment'){
        $array[$j][] = '';
        $array[$j][] = '';
      }
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][]='';
      if(isset($type) && $type=='subcontract_payment'){
        $array[$j][] = '';
      }

    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function delete()
  {
    $data['schedule_id'] = $this->security->xss_clean($this->input->post('schedule_id'));
    $data['delete_status'] = 1;

    $result =  $this->payment_schedule->update_schedule($data);
    $json_data['status'] = $result;
    if ($json_data['status'] == 1) {
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = "Payment Schedule deleted Successfully";
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = "Sorry.. There Have been Some Error Occurred. Please Try Again!";
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !';
    }
    echo json_encode($flash_data);
  }

  public function update()
  {
    $data['type'] = $this->security->xss_clean($this->input->post('type'));
    $data['reference_id'] = $this->security->xss_clean($this->input->post('reference_id'));
    $data['scheduled_amount'] = $this->security->xss_clean($this->input->post('scheduled_amount'));
    $data['scheduled_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('scheduled_date'))));
    $data['stage_no'] = $this->security->xss_clean($this->input->post('stage_no'));
    $data['stage_name'] = $this->security->xss_clean($this->input->post('stage_name'));
    $data['remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $data['reference_type'] = $this->security->xss_clean($this->input->post('reference_type'));
    $data['updated_by'] = $this->session->userdata('user_id');
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['schedule_id'] = $this->security->xss_clean($this->input->post('schedule_id_edit'));

    $result =  $this->payment_schedule->update_schedule($data);
    $json_data['status'] = $result;
    if ($json_data['status'] == 1) {
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = "Payment Schedule Updated Successfully";
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = "Sorry.. There Have been Some Error Occurred. Please Try Again!";
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !';
    }
    echo json_encode($flash_data);

  }

}
