<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Daily_tasks 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('Supplier_model', 'Supplier');
    $this->load->model('Daily_tasks_model', 'Daily_tasks');
    $this->load->model('Daily_reports_model', 'Daily_reports');
    $this->load->library('Push_notification','push_notification');

    $this->load->library('Projects_management','projects_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","auditor","accounts_manager","qs","qs_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }

    //      File Directory
    $this->page_data['directory'] = "daily_tasks";

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

  public function view()
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_daily_task')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    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, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['supervisors'] = $this->User->select_user("",array("role_id >"=>2))->result();
    $this->page_data['page_name'] = 'daily_tasks';

    $this->load->view('Index', $this->page_data);
  }

  public function select_daily_tasks($param=""){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();
    if(isset($_POST['work_id'])){
      $data['dt.work_id'] = $_POST['work_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['dt.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('dt.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $start_date=date('Y-m-d', strtotime($_POST['start_date']));
      $data["STR_TO_DATE(dt.task_due_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $end_date=date('Y-m-d', strtotime($_POST['end_date']));
      $data["STR_TO_DATE(dt.task_due_date,'%Y-%m-%d') <="]= $end_date;
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Tasks only
      $data['dt.user_id'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['user']) && $_POST['user']!='' && $_POST['user']!='all'){
      $data['dt.user_id'] = $_POST['user'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['dt.created_by'] = $_POST['user_id'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      // $data['dt.created_by'] = $this->session->userdata('user_id');
    }

    $result	= $this->Daily_tasks->select("dt.*,u2.user_alias as created_user,u1.user_alias as assigned_to,wc.work_id,wc.work_name",$data);
    $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):
      $id=$row->work_id;
      $btn_add_activity=$btn_update_status='';
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="daily_task_edit_btn" href="#daily_task_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="daily_task_delete_btn" href="#daily_task_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 = '';
      }
      $btn_view='<a style="margin-left: 5px;margin-right: 5px" id="daily_task_view_btn" href="#daily_task_view_modal" data-toggle="modal" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
      <i class="fa fa-eye"></i>
      </a>';

      $btn_activity='<a style="margin-left: 5px;margin-right: 5px" id="activities_view_btn" href="#activities_view_modal" data-toggle="modal" class="btn btn-focus m-btn m-btn--icon btn-sm m-btn--pill m-btn--air">
      <i class="fa fa-tasks"></i> View Acivities
      </a>';
      if($this->session->userdata('user_id')==$row->user_id) {
        $btn_add_activity='<a style="margin-left: 5px;margin-right: 5px" id="daily_task_activity_add_btn" href="#daily_task_activity_add_modal" data-toggle="modal" class="btn btn-focus m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="fa fa-plus-circle"></i>
        </a>';
        $btn_update_status='<a style="margin-left: 5px;margin-right: 5px" id="daily_task_status_update_btn" href="#daily_task_update_status_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="fa fa-edit"></i>
        </a>';
      }

      if($row->task_status==1){
        $task_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Completed</span>";
      }elseif($row->task_status==2){
        $task_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> In Progress</span>";
      }else{
        $task_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
      }
      // Check Task is Due or Not If its Not Completed
      if($row->task_status!=1){
        if(date("Y-m-d") > $row->task_due_date){
          $task_status.="<br/><span style='margin-top: 5px;width: 100%' class='m-spinner m-spinner--focus m-badge m-badge--focus m-badge--wide'> Overdue</span>";
        }
      }

      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]=$row->task_id;
      $array[$j][]='<a href="'.base_url().'user/profile/'.$row->user_id.'">'.$row->assigned_to.'</a>';
      $array[$j][]='<a href="'.base_url().'work/profile/'.$id.'">'.$row->work_name.'</a>';
      $array[$j][]=$row->task_title;
      $array[$j][]=date('d-m-Y',strtotime($row->task_due_date));
      $array[$j][]=$task_status;
      $array[$j][]=$row->task_description;
      $array[$j][]=$btn_activity;
      $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_add_activity.$btn_update_status.$btn_view.$btn_edit.$btn_delete;
      $array[$j][]=$row->work_id;
      $array[$j][]=$row->user_id;
      $array[$j][]=$row->task_status;

      $j++;
    endforeach;

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

  public function create()
  {
    $data['work_id'] = $this->security->xss_clean($this->input->post('work'));
    $data['user_id'] = $this->security->xss_clean($this->input->post('assigned_to'));
    $data['task_title'] = $this->security->xss_clean($this->input->post('title'));
    $data['task_due_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('due_date'))));
    $data['task_description'] = $this->security->xss_clean($this->input->post('description'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $data['project_stage_id'] = $this->projects_management->get_project_stage_id($data['work_id']);

    $result =  $this->Daily_tasks->create($data);
    $flash_data['status'] = $result['status'];
    if ($result['status'] == 1) {

      // Send Push Notification to App User
      $work_data = $this->Work->select_work("*", array("work_id" => $data['work_id']))->row();
      $message = "You Have been Assigned to a New Task in Project '$work_data->work_name'. Please Check.";
      $this->push_notification->send_notification($data['user_id'],$message,"New Task Assigned",$result['insert_id']);

      $flash_data['flashdata_msg'] = 'New Daily Task Added 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 !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);

  }
  public function update()
  {
    $data['task_id'] = $this->security->xss_clean($this->input->post('task_id'));
    $data['work_id'] = $this->security->xss_clean($this->input->post('work'));
    $data['user_id'] = $this->security->xss_clean($this->input->post('assigned_to'));
    $data['task_title'] = $this->security->xss_clean($this->input->post('title'));
    $data['task_due_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('due_date'))));
    $data['task_description'] = $this->security->xss_clean($this->input->post('description'));
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');

    $result =  $this->Daily_tasks->update($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'Daily Task Details 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 !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);

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

    $result =  $this->Daily_tasks->update($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'Daily Task 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 !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);

  }
  public function update_status()
  {
    $data['task_id'] = $this->security->xss_clean($this->input->post('task_id'));
    $data['task_status'] = $this->security->xss_clean($this->input->post('task_status'));

    $result =  $this->Daily_tasks->update($data);
    $flash_data['status'] = $result;
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'Daily Task Status 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 !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);

  }

  public function create_activity()
  {
    $data['task_id'] = $this->security->xss_clean($this->input->post('task_id'));
    $data['report_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('date'))));
    $data['description'] = $this->security->xss_clean($this->input->post('description'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');

    $result =  $this->Daily_reports->create_task_report($data);
    $flash_data['status'] = $result['status'];
    if ($result['status'] == 1) {

      $flash_data['flashdata_msg'] = 'Activity Added 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 !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);

  }

  public function select_daily_task_report($param=""){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();
    if(isset($_POST['work_id'])){
      $data['dt.work_id'] = $_POST['work_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['dt.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('dt.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['task_id'])){
      $data['dr.task_id'] = $_POST['task_id'];
    }
    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(dr.report_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(dr.report_date,'%Y-%m-%d') >="]= $start_date;
    }
    if($this->session->userdata('user_role')!='auditor' && $this->session->userdata('user_role')!='admin' ) {
      $data['dr.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['dr.created_by'] = $_POST['user_id'];
    }
    $result	= $this->Daily_reports->select_task_report("dr.*,dt.task_title,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",$data);
    $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):
      $id=$row->work_id;
      $btn_edit = $btn_delete = $btn_view = "";
      // if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by) {
      //   $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="daily_report_edit_btn" href="#daily_report_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="daily_report_delete_btn" href="#daily_report_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 = '';
      // }
      // $btn_view='<a style="margin-left: 5px;margin-right: 5px" id="daily_report_view_btn" href="#daily_report_view_modal" data-toggle="modal" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
      // <i class="fa fa-eye"></i>
      // </a>';

      if($row->activity_location_address!=''){
        $activity_data['location'] = $row->activity_location_address;
        $activity_data['landmark'] = $row->activity_location_landmark;
        $activity_data['latitude'] = $row->activity_location_latitude;
        $activity_data['longitude'] = $row->activity_location_longitude;
        if($activity_data['latitude']!='' && $activity_data['longitude']!=''){
          $activity_data['location'] .= '<br/><a target="_blank" style="margin-left: 5px;margin-right: 5px"  href="https://www.google.com/maps/search/?api=1&map_action=map&query='.$activity_data['latitude'].','.$activity_data['longitude'].'&zoom=16" class="btn btn-info m-btn m-btn--icon  btn-sm m-btn--pill m-btn--air"><i class="fa fa-map-marker"></i> View on Map</a>';
        }
      }else{
        $activity_data['location'] = '';
      }



      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]=$row->report_id;
      $array[$j][]=$row->work_id;
      $array[$j][]=$row->task_title;
      $array[$j][]='<a href="'.base_url().'work/profile/'.$id.'">'.$row->work_name.'</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->report_date));
      $array[$j][]=$row->description;
      $array[$j][]=$activity_data['location'];
      $array[$j][]=$row->user_alias;
      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_view.$btn_edit.$btn_delete;
      $j++;
    endforeach;

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