<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Documents 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('Documents_model', 'Documents');
    $this->load->model('Work_model', 'Work');

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

    // Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","boq_manager","sales_manager","purchase_manager","sales_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'] = "documents";

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

  public function view()
  {
    // Check Module is Enabled or Not

    $this->page_data['page_name'] = 'documents_view';
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['users'] = $this->User->select_user("","")->result();
    $this->load->view('Index',$this->page_data);
  }

  public function select_documents($list_type=""){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=0;
    $data=array();
    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(pd.created_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(pd.created_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['user']) && $_POST['user']!='' && $_POST['user']!='all'){
      $data['pd.created_by'] = $_POST['user'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['pd.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('pd.work_id',explode(',',$_POST['work_ids']));
    }
    $result	= $this->Documents->select_documents("*,pd.created_date AS pd_created_date,pd.created_by AS pd_created_by",$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):
      $visibility_status='All';
      $state='true';
      if($row->visibility==0){
        $visibility_status='Admins Only';
        $state='false';
      }
      $is_url = 0;
      $filename = base_url().'uploads/documents/'.$row->filename;

      if(filter_var($row->filename, FILTER_VALIDATE_URL)){
        $filename = $row->filename;
        $is_url = 1;
      }

      $file = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="'.$filename.'" >Click To view</a>';

      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_id')== $row->pd_created_by ) {

        $btn_edit = '<a onclick="$(\'#visible_status_edit\').bootstrapSwitch(\'state\', '.$state.', true);" style="margin-left: 5px;margin-right: 5px" id="document_edit_btn" href="#document_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 onclick="$(\'#id_delete\').val(\'' . $row->id . '\');" style="margin-left: 5px;margin-right: 5px" id="document_delete_btn" href="#document_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='';

      }
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')== $row->pd_created_by || $row->visibility!=0 ){

        $sl_no++;
        $array[$j][]=$sl_no;
        $array[$j][]="#".$row->id;
        $array[$j][]=$row->work_name;
        $array[$j][]=$row->title;
        $array[$j][]=$row->description;
        $array[$j][]=$file;
        $array[$j][]=$visibility_status;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->pd_created_date))."</li><li>Created By : ".$row->user_alias."</li>";
        }else{
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
        }
        $array[$j][]=$btn_edit.$btn_delete;
        $array[$j][]=$row->id;
        $array[$j][]=$row->work_id;
        $array[$j][]=$is_url;
        $array[$j][]=$filename;

      }
      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select(){
    $data = array();
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['pd.work_id'] = $_POST['work'];
    }
    $result	= $this->Documents->select_documents("*,pd.created_date AS pd_created_date,pd.created_by AS pd_created_by",$data);
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->result()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function create()
  {
    $data2['title'] = $this->security->xss_clean($this->input->post('title'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);

    $visibility = $this->security->xss_clean($this->input->post('visible_status'));
    if($visibility == 'on'){
      $data2['visibility'] = 1;
    }else{
      $data2['visibility'] = 0;
    }
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');

    $file_error = 0;
    // if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
    //   //      File Upload
    //   $config['upload_path']   = 'uploads/documents/';
    //   $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx|xls|xl|xlsx|odt|ods|ppt|pptx|txt|csv';
    //   $config['max_size']      = 3000;
    //   $config['encrypt_name']    = TRUE;
    //   $this->load->library('upload', $config);
    // if ( ! $this->upload->do_upload('uploaded_file')) {
    //   $error = array('error' => $this->upload->display_errors());
    //   $file_error = 1;
    //   $flash_data['flashdata_msg'] = $error['error'];
    //   $flash_data['flashdata_type'] = "warning";
    //   $flash_data['flashdata_title'] = "Uploaded File Error";
    //   $flash_data['status'] = 2;
    // }else {
    // $file_data = $this->upload->data();
    // $data2['filename'] = $file_data['file_name'];
    $data2['filename'] = $this->security->xss_clean($this->input->post('file'));;

    $result2 = $this->Documents->create_document($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Document Added Succesfully';
      $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 !!';
    }
    // }
    // }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()
  {

    $data2['title'] = $this->security->xss_clean($this->input->post('title'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    if($this->security->xss_clean($this->input->post('work_id_edit'))){
      $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id_edit'));
    }
    $data2['id'] = $this->security->xss_clean($this->input->post('id_edit'));
    $visibility = $this->security->xss_clean($this->input->post('visible_status'));
    if($visibility == 'on'){
      $data2['visibility'] = 1;
    }else{
      $data2['visibility'] = 0;
    }

    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');
    $result2 = $this->Documents->update_document($data2);

    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Project Documents Updated Succesfully';
      $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 delete()
  {
    //  Delete Received Amount
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['id'] = $this->security->xss_clean($this->input->post('id_delete'));
    $data2['delete_status']=1;
    $result2 = $this->Documents->update_document($data2);

    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Project Document Deleted Succesfully';
      $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 create_revision()
  {
    $data3['document_id'] = $this->security->xss_clean($this->input->post('document_id'));
    $data3['revision_no'] = $this->security->xss_clean($this->input->post('revision_no'));
    $data3['send_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('send_date'))));
    $data3['client_feedback'] = $this->security->xss_clean($this->input->post('feedback'));
    $data3['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data3['revision_status'] = $this->security->xss_clean($this->input->post('revision_status'));
    $data3['created_date'] = date('Y-m-d H:i:s');
    $data3['created_by'] = $this->session->userdata('user_id');
    $count = $this->Documents->select_document_revision('revision_id',array("pdr.document_id"=>$data3['document_id'],"pdr.revision_no"=>$data3['revision_no']));
    if($count->num_rows()==0){
      $result = $this->Documents->insert_document_revision($data3);
      $flash_data['status'] = $result['status'];
      if($result['status'] == 1){
        $flash_data['flashdata_msg'] = 'Document Revision 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 !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. A Revision With Same Revision No Already Exist for this Project!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function update_revision()
  {
    $document_id = $this->security->xss_clean($this->input->post('document_id'));
    $data3['revision_id'] = $this->security->xss_clean($this->input->post('revision_id'));
    $data3['revision_no'] = $this->security->xss_clean($this->input->post('revision_no'));
    $data3['send_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('send_date'))));
    $data3['client_feedback'] = $this->security->xss_clean($this->input->post('feedback'));
    $data3['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data3['revision_status'] = $this->security->xss_clean($this->input->post('revision_status_edit'));
    $count = $this->Documents->select_document_revision('revision_id',array("pdr.revision_no !="=>$data3['revision_no'],"pdr.document_id"=>$document_id,"pdr.revision_no"=>$data3['revision_no']));
    if($count->num_rows()==0){
      $result = $this->Documents->update_document_revision($data3);
      $flash_data['status'] = $result;
      if($result == 1){
        $flash_data['flashdata_msg'] = 'Document Revision 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 !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. A Revision With Same Revision No Already Exist for this Project!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function select_document_revisions(){

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

    $data=array();

    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['pd.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('pd.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['user']) && $_POST['user']!='' && $_POST['user']!='all'){
      $data['pdr.created_by'] = $_POST['user'];
    }
    $result	= $this->Documents->select_document_revision("pdr.*,wc.work_name,pd.filename,pd.id,pd.title,pd.description,u.user_alias",$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):

      $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="document_revision_edit_btn" href="#document_revision_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='';
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='madmin'  ) {
        // $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="document_revision_delete_btn" href="#document_revision_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>';
      }

      $filename = base_url().'uploads/documents/'.$row->filename;

      if(filter_var($row->filename, FILTER_VALIDATE_URL)){
        $filename = $row->filename;
        $is_url = 1;
      }

      $file = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="'.$filename.'" >Click To view</a>';


      if($row->revision_status==1){
        $revision_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
      }elseif($row->revision_status==2){
        $revision_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Rejected</span>";
      }elseif($row->revision_status==3){
        $revision_status="<span class='m-badge m-badge--info m-badge--wide'><i class='la la-refresh'></i> Need Changes</span>";
      }else{
        $revision_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
      }

      $sl_no++;
      $array[$j][]=$row->revision_id;
      $array[$j][]="#".$row->id." - ".$row->title;
      $array[$j][]=$row->work_name;
      $array[$j][]=$row->description;
      $array[$j][]=$file;
      $array[$j][]=$row->revision_no;
      $array[$j][]=date('d-m-Y',strtotime($row->send_date));
      $array[$j][]=$row->client_feedback;
      $array[$j][]=$row->remarks;
      $array[$j][]=$revision_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->id;
      $array[$j][]=$row->revision_status;

      $j++;
    endforeach;

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

}
?>
