<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Notifications extends CI_Controller {

  public $page_data=array();

  function __construct()
  {
    parent::__construct();
    //Calling Initial Functions
    $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('Project_tasks_model', 'Project_tasks');
    $this->load->model('Payment_schedule_model', 'payment_schedule');
    $this->load->model('Enquiries_model','Enquiries');
    $this->load->model('Daily_reports_model', 'Daily_reports');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Purchase_request_model', 'Purchase_request');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Sales_quotation_model','Sales_quotation');
    $this->load->model('Work_order_model','Work_order');
    $this->load->model('Reminders_model', 'Reminders');
    $this->load->library('Projects_management','projects_management');
    //        File Directory
    $this->page_data['directory'] = "notifications";
    $this->page_data['user_role'] = $this->session->userdata('user_role');
    $this->page_data['user_directory'] = $this->session->userdata('user_role')."/";

  }

  public function index($page_template='')
  {
    $this->notification($page_template);
  }
  public function notification($page_template='')
  {
    $this->page_data['notifications_count'] = $this->page_data['reminders_count'] = $this->page_data['purchase_notifications_count'] = $this->page_data['notification_2_count'] = $this->page_data['vehicle_notifications'] = 0;
    $this->page_data['sales_quotations_approved'] = $this->page_data['client_payment_notifications'] = $this->page_data['daily_notes'] = $this->page_data['vehicle_renewals'] = array();
    $date=date('Y-m-d');

    $reminder_where['r.reminder_date <='] = date('Y-m-d',strtotime("+7 days"));
    $this->page_data['reminders'] = $this->Reminders->select_reminders("r.*,u.user_alias,wc.work_name,e.employee_name,e.user_designation,l.labour_name,v.vehicle_no,v.vehicle_name",$reminder_where);
    $this->page_data['reminders_count'] = $this->page_data['reminders']->num_rows();
    $this->page_data['payment_schedules_client'] = $this->payment_schedule->select_schedule("ps.*,wc.*,u.user_alias as created_user",array('ps.scheduled_date <=' => $date,'ps.type'=>'client_payment'),'work');
    $this->page_data['payment_schedules_subcontract'] = $this->payment_schedule->select_schedule("ps.*,wc.*,u.user_alias as created_user",array('ps.scheduled_date <=' => $date,'ps.type'=>'subcontract_payment'),'subcontract');
    $this->page_data['enquiry_followups'] = $this->Enquiries->select_enquiry_followups("ef.*,s.service_name,c.customer_name",array('ef.followup_status'=>0,'ef.followup_date >=' => $date." 00:00:00",'ef.followup_date <=' => $date." 23:59:00"));
    if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='accounts_manager') {
      $this->page_data['leave_applications'] = $this->Employee->select_employee_leave_applications("la.*,e.employee_name",array("la.approval_status_1"=>0));
      $this->page_data['notifications_count'] += $this->page_data['leave_applications']->num_rows();
      if($this->config->item('Daily_Note_notification')==1){
        $this->page_data['daily_notes'] = $this->Daily_reports->select_daily_notes("dn.*,u.user_alias,wc.work_id,wc.work_name,ua.activity_location_address,ua.activity_location_landmark,ua.activity_location_latitude,ua.activity_location_longitude",array("read_status"=>0));
        $this->page_data['notification_2_count'] += $this->page_data['daily_notes']->num_rows();
      }
    }
    $purchase_request_1st_level_approval_roles = explode(',',$this->config->item('Approvals_purchase_request_1st_level'));
    $purchase_request_2nd_level_approval_roles = explode(',',$this->config->item('Approvals_purchase_request_2nd_level'));
    if(in_array($this->session->userdata('user_role'), $purchase_request_1st_level_approval_roles)){
      $this->page_data['purchase_request_pending'] = $this->Purchase_request->select_purchase_request("pr.*,pr.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u2.user_alias as approved_user",array("pr.approval_status_1"=>0));
      $this->page_data['purchase_notifications_count'] += $this->page_data['purchase_request_pending']->num_rows();
    }
    if($this->config->item('Purchase_purchase_request_second_approval')==1 && in_array($this->session->userdata('user_role'), $purchase_request_2nd_level_approval_roles)) {
      $this->page_data['purchase_request_pending'] = $this->Purchase_request->select_purchase_request("pr.*,pr.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u2.user_alias as approved_user",array("pr.approval_status_1"=>1,"pr.approval_status_2"=>0));
      $this->page_data['purchase_notifications_count'] += $this->page_data['purchase_request_pending']->num_rows();
    }
    if($this->config->item('Purchase_request_payment_released_status')==1 && $this->session->userdata('user_role')=='accounts_manager'){
      $this->page_data['purchase_request_pending'] = $this->Purchase_request->select_purchase_request("pr.*,pr.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u2.user_alias as approved_user",array("pr.approval_status_2"=>1,"pr.payment_released_status"=>0));
      $this->page_data['purchase_notifications_count'] += $this->page_data['purchase_request_pending']->num_rows();
    }
    $this->page_data['notifications_count'] += $this->page_data['payment_schedules_client']->num_rows()+$this->page_data['payment_schedules_subcontract']->num_rows()+$this->page_data['enquiry_followups']->num_rows();
    if($this->config->item('app_module_vehicle_management')==1){
      $vehicle_renewals = array();
      $vn = 0;
      // Check EMI
      $emi_where['v.emi_status'] = 1;
      $emi_where['v.next_emi_renewal_date !='] = '0000-00-00';
      $emi_where['v.next_emi_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_emi_reminder_days_before')." days"));
      $emi_renewals = $this->Vehicle->select_vehicle('v.*',$emi_where)->result();
      foreach ($emi_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'EMI';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->next_emi_renewal_date;
        $vn++;
      }

      // Check Insurance
      $insurance_where['v.insurance_renewal_date !='] = '0000-00-00';
      $insurance_where['v.insurance_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_insurance_reminder_days_before')." days"));
      $insurance_renewals = $this->Vehicle->select_vehicle('v.*',$insurance_where)->result();
      foreach ($insurance_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Insurance';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->insurance_renewal_date;
        $vn++;
      }

      // Check Tax
      $tax_where['v.tax_renewal_date !='] = '0000-00-00';
      $tax_where['v.tax_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_tax_reminder_days_before')." days"));
      $tax_renewals = $this->Vehicle->select_vehicle('v.*',$tax_where)->result();
      foreach ($tax_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Tax';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->tax_renewal_date;
        $vn++;
      }

      // Check Permit
      $permit_where['v.permit_renewal_date !='] = '0000-00-00';
      $permit_where['v.permit_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_permit_reminder_days_before')." days"));
      $permit_renewals = $this->Vehicle->select_vehicle('v.*',$permit_where)->result();
      foreach ($permit_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Permit';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->permit_renewal_date;
        $vn++;
      }

      // Check Break
      $break_where['v.break_renewal_date !='] = '0000-00-00';
      $break_where['v.break_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_break_reminder_days_before')." days"));
      $break_renewals = $this->Vehicle->select_vehicle('v.*',$break_where)->result();
      foreach ($break_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Break';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->break_renewal_date;
        $vn++;
      }

      // Check Fitness
      $fitness_where['v.fitness_renewal_date !='] = '0000-00-00';
      $fitness_where['v.fitness_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_fitness_reminder_days_before')." days"));
      $fitness_renewals = $this->Vehicle->select_vehicle('v.*',$fitness_where)->result();
      foreach ($fitness_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Fitness';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->fitness_renewal_date;
        $vn++;
      }

      // Check pollution
      $pollution_where['v.pollution_renewal_date !='] = '0000-00-00';
      $pollution_where['v.pollution_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_pollution_reminder_days_before')." days"));
      $pollution_renewals = $this->Vehicle->select_vehicle('v.*',$pollution_where)->result();
      foreach ($pollution_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Pollution';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->pollution_renewal_date;
        $vn++;
      }

      // Check gps
      $gps_where['v.gps_renewal_date !='] = '0000-00-00';
      $gps_where['v.gps_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_gps_reminder_days_before')." days"));
      $gps_renewals = $this->Vehicle->select_vehicle('v.*',$gps_where)->result();
      foreach ($gps_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'GPS';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->gps_renewal_date;
        $vn++;
      }

      // Check speed_governor
      $speed_governor_where['v.speed_governor_renewal_date !='] = '0000-00-00';
      $speed_governor_where['v.speed_governor_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_speed_governor_reminder_days_before')." days"));
      $speed_governor_renewals = $this->Vehicle->select_vehicle('v.*',$speed_governor_where)->result();
      foreach ($speed_governor_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Speed Governor';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->speed_governor_renewal_date;
        $vn++;
      }

      // Check welfare
      $welfare_where['v.welfare_renewal_date !='] = '0000-00-00';
      $welfare_where['v.welfare_renewal_date <='] = date('Y-m-d',strtotime("+".$this->config->item('Vehicle_welfare_reminder_days_before')." days"));
      $welfare_renewals = $this->Vehicle->select_vehicle('v.*',$welfare_where)->result();
      foreach ($welfare_renewals as $key => $value) {
        $vehicle_renewals[$vn]['type'] = 'Welfare';
        $vehicle_renewals[$vn]['vehicle_id'] = $value->id;
        $vehicle_renewals[$vn]['vehicle_no'] = $value->vehicle_no;
        $vehicle_renewals[$vn]['vehicle_name'] = $value->vehicle_name;
        $vehicle_renewals[$vn]['renewal_date'] = $value->welfare_renewal_date;
        $vn++;
      }

      $this->page_data['vehicle_renewals'] = $vehicle_renewals;
      $this->page_data['vehicle_notifications'] = sizeof($this->page_data['vehicle_renewals']);
    }
    if($this->config->item('app_module_sales_quotation')==1){
      $sales_quotations_approved = array();
      $sq=0;
      $sales_quotations = $this->Sales_quotation->select_quotations("sq.*,u.user_alias",array("sq.approval_status"=>1))->result();
      foreach($sales_quotations as $row){
        $work_order_count = $this->Work_order->select_work_orders("*", array("wo.quotation_id"=>$row->quotation_id))->num_rows();
        if($work_order_count==0){
          $sales_quotations_approved[$sq]['quotation_id'] = $row->quotation_id;
          $sales_quotations_approved[$sq]['user'] = $row->user_alias;
          $sales_quotations_approved[$sq]['customer_name'] = $row->customer_name;
          $sales_quotations_approved[$sq]['quotation_date'] = date('d-m-Y',strtotime($row->date));
          $sq++;
        }
      }
      $this->page_data['sales_quotations_approved'] = $sales_quotations_approved;
    }

    if($this->config->item('Purchase_purchase_order_approval')==1){
      if($this->session->userdata('user_role')=='project_manager' || $this->session->userdata('user_role')=='admin') {
        $this->page_data['purchase_order_pending'] = $this->Purchase_order->select_purchase_order("po.*,po.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u2.user_alias as approved_user",array("po.approval_status_1"=>0));
        $this->page_data['purchase_notifications_count'] += $this->page_data['purchase_order_pending']->num_rows();
      }
      if($this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='admin') {
        $this->page_data['purchase_order_pending'] = $this->Purchase_order->select_purchase_order("po.*,po.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u2.user_alias as approved_user",array("po.approval_status_1"=>1,"po.approval_status_2"=>0));
        $this->page_data['purchase_notifications_count'] += $this->page_data['purchase_order_pending']->num_rows();
      }
    }

    $cp = 0;
    $client_payment_notifications = array();
    if($this->config->item('Client_Payment_client_payment_due_notification')==1){
      $projects  = $this->Work->select_work("w.*,c.client_name")->result();
      foreach ($projects as $row){
        $work_status = $row->work_status;
        $report_data = $this->projects_management->get_project_summary($row->work_id);
        if($report_data!=''){
          if($row->work_status==1 && $report_data['balance_to_receive']>0){
            $client_payment_notifications[$cp]['type'] = 'completed_project_payment_pending';
            $client_payment_notifications[$cp]['work_id'] = $row->work_id;
            $client_payment_notifications[$cp]['work_name'] = $row->work_name;
            $client_payment_notifications[$cp]['client_name'] = $row->client_name;
            $client_payment_notifications[$cp]['total_project_cost'] = $report_data['total_project_cost'];
            $cp++;
          }
          if($row->work_status!=1 && $report_data['total_project_cost']>$report_data['total_client_payments_received']){
            $client_payment_notifications[$cp]['type'] = 'project_cost_exceeded_payment_pending';
            $client_payment_notifications[$cp]['work_id'] = $row->work_id;
            $client_payment_notifications[$cp]['work_name'] = $row->work_name;
            $client_payment_notifications[$cp]['client_name'] = $row->client_name;
            $client_payment_notifications[$cp]['total_project_cost'] = $report_data['total_project_cost'];
            $cp++;
          }
        }
      }
    }
    $this->page_data['client_payment_notifications'] = $client_payment_notifications;
    $this->load->view('includes/Inc_notifications'.$page_template,$this->page_data);
  }


}
