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

class Sales_targets 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('Sales_quotation_model', 'Sales_quotation');
    $this->load->model('Sales_targets_model', 'Sales_targets');
    $this->load->model('Work_order_model', 'Work_order');

    //        File Directory
    $this->page_data['directory'] = "sales_targets";
  }
  public function index()
  {
    $this->view();
  }

  public function view()
  {
    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin", "admin", "sales_manager", "general_manager", "supervisor");
    if ($this->User->is_logged_in($allowed_user_roles) == false) {
      redirect(base_url(), 'refresh');
    }

    $this->page_data['sales_staffs'] = $this->User->Select_user('*', array('user_role' => 25))->result();

    // exit(print_r($this->page_data['sales_staffs']));

    $this->page_data['page_name'] = 'sales_targets_view';
    $this->load->view('Index', $this->page_data);
  }

  public function report()
  {
    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin", "admin", "sales_manager", "general_manager", "supervisor");
    if ($this->User->is_logged_in($allowed_user_roles) == false) {
      redirect(base_url(), 'refresh');
    }

    $this->page_data['sales_staffs'] = $this->User->Select_user('*', array('user_role' => 25))->result();

    $this->page_data['page_name'] = 'sales_target_report';
    $this->load->view('Index', $this->page_data);
  }


  public function get_sales_target_report()
  {
    $data['st.user_id'] = $this->input->post('staff');
    $data['st.month'] = $where_start = date('Y-m-01', strtotime($this->input->post('month')));
    $where_end = date('Y-m-t', strtotime($this->input->post('month')));


    $response['target_data'] = $this->Sales_targets->select_targets("st.*,u2.username as staff_email,u2.phone_no as sales_staff_phone_no,u2.user_id as staff_id,u2.user_alias as sales_staff,u.user_alias as created_by", $data)->row();

    if ($response['target_data']) {

      $response['target_details'] = $this->Sales_targets->select_target_items("std.*,st.target_type", $data)->result();

      // product

      $data_sq_product['sq.prepared_by'] = $data['st.user_id'];
      $data_sq_product['sq.quotation_type'] = 'product';
      $data_sq_product['sq.date >= '] = $where_start;
      $data_sq_product['sq.date <= '] = $where_end;
      $product['total_amount'] = $this->Sales_quotation->select_quotation_items("COALESCE(SUM(sqi.total_amount),0) as total_amount", $data_sq_product)->row()->total_amount;

      $data_p = $data;
      $data_p['std.target_amount<='] = $product['total_amount'];
      $data_p['st.target_type'] = 'product';
      // $this->db->select_max('std.target_amount');
      $target_details = $this->Sales_targets->select_target_items("std.*,st.target_type", $data_p)->result();
      if (!empty($target_details)) {
        $max = $product['total_amount'];
        foreach ($target_details as $key => $td) {
          if ($td->target_amount >= $max) {
            $target_details = $td;
          } else {
            $max = $td->target_amount;
          }
        }
        $product['target_details'] = $target_details;
        $product['target_amount'] = $product['total_amount'] * $target_details->incentive_percent * 0.01;
      } else {
        $product['target_details'] = array();
        $product['target_amount'] = 0;
      }
      // service

      $data_sq_service['sq.prepared_by'] = $data['st.user_id'];
      $data_sq_service['sq.quotation_type'] = 'service';
      $data_sq_service['sq.date >= '] = $where_start;
      $data_sq_service['sq.date <= '] = $where_end;
      $service['total_amount'] = $this->Sales_quotation->select_quotation_items("COALESCE(SUM(sqi.total_amount),0) as total_amount", $data_sq_product)->row()->total_amount;

      $data_s = $data;
      $data_s['std.target_amount<='] = $service['total_amount'];
      $data_s['st.target_type'] = 'service';
      // $this->db->select_max('std.target_amount');
      $target_details = $this->Sales_targets->select_target_items("std.*,st.target_type", $data_s)->result();
      if (!empty($target_details)) {
        $max = $service['total_amount'];
        foreach ($target_details as $key => $td) {
          // exit(print_r($td));
          if ($td->target_amount >= $max) {
            $target_details = $td;
          } else {
            $max = $td->target_amount;
          }
        }
        $service['target_details'] = $target_details;
        $service['target_amount'] = $service['total_amount'] * $target_details->incentive_percent * 0.01;
      } else {
        $service['target_details'] = array();
        $service['target_amount'] = 0;
      }
      $sq_product_target = $product;
      $sq_service_target = $service;


      $table = '<div class="table-responsive float-center"><table class="table m-table table-bordered item_table" style="margin-left: auto;margin-right:auto; max-width: 60% !important;"><tbody><tr><th colspan="4" style="text-align: center;"><strong>';
      $table .= 'Sales Quotation Sale Target Achievements';
      $table .= '</strong></th></tr><tr><th>Type</th> <th>Sales Amount</th> <th>Eligible Incentive</th> <th>Total Incentive </th> </tr> <tr> <td>Product</td> <td>';
      $table .= $sq_product_target['total_amount'];
      $table .= '</td><td>';
      $table .= empty($sq_product_target['target_details']->incentive_percent) ? 0 : $sq_product_target['target_details']->incentive_percent;
      $table .= '% </td><td>';
      $table .= $sq_product_target['target_amount'];
      $table .= '</td></tr><tr><td>Service</td><td>';
      $table .= $sq_service_target['total_amount'];
      $table .= '</td><td>';
      $table .= empty($sq_service_target['target_details']->incentive_percent) ? 0 : $sq_service_target['target_details']->incentive_percent;
      $table .= ' %</td><td>';
      $table .= $sq_service_target['target_amount'];
      $table .= '</td></tr><tr><td colspan="3" style="text-align: right;">Total</td><td>';
      $table .= $sq_product_target['target_amount'] + $sq_service_target['target_amount'];
      $table .= '</td></tr></tbody></table></div>';



      // product

      $data_wo_product['sq.prepared_by'] = $data['st.user_id'];
      $data_wo_product['sq.quotation_type'] = 'product';
      $data_wo_product['wo.order_date >= '] = $where_start;
      $data_wo_product['wo.order_date <= '] = $where_end;
      $product['total_amount'] = $this->Work_order->select_work_orders("COALESCE(SUM(wo.grand_total_amount),0) as total_amount", $data_wo_product)->row()->total_amount;

      // if ($product['total_amount'] > 0) {

      $data_p = $data;
      $data_p['std.target_amount<='] = $product['total_amount'];
      $data_p['st.target_type'] = 'product';
      // $this->db->select_max('std.target_amount');
      $target_details = $this->Sales_targets->select_target_items("std.*,st.target_type", $data_p)->result();
      if (!empty($target_details)) {
        $max = $product['total_amount'];
        foreach ($target_details as $key => $td) {
          if ($td->target_amount >= $max) {
            $target_details = $td;
          } else {
            $max = $td->target_amount;
          }
        }
        $product['target_details'] = $target_details;
        $product['target_amount'] = $product['total_amount'] * $target_details->incentive_percent * 0.01;
      } else {
        $product['target_details'] = array();
        $product['target_amount'] = 0;
      }

      // service

      $data_wo_service['sq.prepared_by'] = $data['st.user_id'];
      $data_wo_service['sq.quotation_type'] = 'service';
      $data_wo_service['wo.order_date >= '] = $where_start;
      $data_wo_service['wo.order_date <= '] = $where_end;
      $service['total_amount'] = $this->Work_order->select_work_orders("COALESCE(SUM(wo.grand_total_amount),0) as total_amount", $data_wo_service)->row()->total_amount;

      $data_s = $data;
      $data_s['std.target_amount<='] = $service['total_amount'];
      $data_s['st.target_type'] = 'service';

      // $this->db->select_max('std.target_amount');
      $target_details = $this->Sales_targets->select_target_items("std.*,st.target_type", $data_s)->result();
      if (!empty($target_details)) {
        $max = $service['total_amount'];
        foreach ($target_details as $key => $td) {
          if ($td->target_amount >= $max) {
            $target_details = $td;
          } else {
            $max = $td->target_amount;
          }
        }
        $service['target_details'] = $target_details;
        $service['target_amount'] = $service['total_amount'] * $target_details->incentive_percent * 0.01;
      } else {
        $service['target_details'] = array();
        $service['target_amount'] = 0;
      }

      $wo_product_target = $product;
      $wo_service_target = $service;


      $table .= '<div class="table-responsive float-center mt-10"><table class="table m-table table-bordered item_table" style="margin-left: auto;margin-right:auto; max-width: 60% !important;"><tbody><tr><th colspan="4" style="text-align: center;"><strong>';
      $table .= 'Work Order Sale Target Achievements';
      $table .= '</strong></th></tr><tr><th>Type</th> <th>Sales Amount</th> <th>Eligible Incentive</th> <th>Total Incentive </th> </tr> <tr> <td>Product</td> <td>';
      $table .= $wo_product_target['total_amount'];
      $table .= '</td><td>';
      $table .= empty($wo_product_target['target_details']->incentive_percent) ? 0 : $wo_product_target['target_details']->incentive_percent;
      $table .= '% </td><td>';
      $table .= $wo_product_target['target_amount'];
      $table .= '</td></tr><tr><td>Service</td><td>';
      $table .= $wo_service_target['total_amount'];
      $table .= '</td><td>';
      $table .= empty($wo_service_target['target_details']->incentive_percent) ? 0 : $wo_service_target['target_details']->incentive_percent;
      $table .= ' %</td><td>';
      $table .= $wo_service_target['target_amount'];
      $table .= '</td></tr><tr><td colspan="3" style="text-align: right;">Total</td><td>';
      $table .= $wo_product_target['target_amount'] + $wo_service_target['target_amount'];
      $table .= '</td></tr></tbody></table></div>';
      // }

      $response['table'] = $table;
    } else {
      $response['status'] = 0;
      $response['message'] = 'No Sales Targets found';
    }




    echo json_encode($response);
  }





  public function create()
  {

    $data['month'] = $data2['st.month'] = date('Y-m-01', strtotime($this->security->xss_clean($this->input->post('month'))));
    $data['user_id'] = $data2['st.user_id'] = $this->security->xss_clean($this->input->post('sales_staff'));
    $data['target_type'] = $data2['target_type'] = $this->security->xss_clean($this->input->post('sales_target_type'));

    $count = $this->Sales_targets->select_targets('*', $data2)->num_rows();
    if ($count == 0) {

      $data['created_by'] = $this->session->userdata('user_id');
      $data['created_date'] = date('Y-m-d H:i:s');

      $result = $this->Sales_targets->insert_target($data);

      $items_array = $newArrayterms = array();
      if ($this->input->post('items')) {
        $items_array = $this->input->post('items');
      }
      $items_array_array_length = sizeof($items_array);
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key => $value) {
          $newArrayterms[$key][$fieldKey] = $value;
        }
      }

      foreach ($newArrayterms as $key => $item) {
        $item['target_id'] = $result['insert_id'];
        $this->Sales_targets->insert_target_item($item);
      }

      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = 'Sales Target Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['target_id'] = $result['insert_id'];
    } else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Already added !';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Duplicate !!';
    }

    echo (json_encode($flash_data));
  }


  public function select_sales_targets($type = '')
  {
    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = array();
    if ($this->config->item('user_data_access_view_all') != 1) {
      $data['st.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['st.created_by'] = $this->session->userdata('user_id');
    }
    if (isset($_POST['staff']) && $_POST['staff'] != '' && $_POST['staff'] != 'all') {
      $data['u2.user_id'] = $_POST['staff'];
    }

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

    if (isset($_POST['month']) && $_POST['month'] != '' && $_POST['month'] != 'all') {
      $data['st.month'] = date('Y-m-01', strtotime($_POST['month']));
    }


    $result = $this->Sales_targets->select_targets("st.*,u2.user_id as staff_id,u2.user_alias as sales_staff,u.user_alias as 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) :

      $btn_edit = $btn_delete = $btn_approve = '';

      if ($this->session->userdata('user_role') != 'auditor') {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="sales_target_edit_btn" href="#sales_target_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="sales_target_delete_btn" href="#sales_target_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>';
      }

      $item_details = '';
      $items = $this->Sales_targets->select_target_items("std.*", array("std.target_id" => $row->target_id))->result();
      foreach ($items as $key => $value) {
        $item_details .= $value->target_amount . '[ Incentive ' . $value->incentive_percent . '% ]<br/>';
      }

      $array[$j][] = $j + 1;
      $array[$j][] = $row->target_id;
      $array[$j][] = $row->sales_staff;
      $array[$j][] = date('F Y', strtotime($row->month));
      $array[$j][] = ucfirst($row->target_type);
      $array[$j][] = $item_details;
      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->created_by . "</li>";
      }else{
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : ' . $row->created_by . '</li>';
      }
      $array[$j][] = $btn_edit . $btn_delete;
      $array[$j][] = $row->staff_id;
      $array[$j][] = json_encode($items);

      $j++;
    endforeach;

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

  public function delete_target()
  {

    $data['target_id'] = $this->security->xss_clean($this->input->post('sales_target_id'));
    $data['delete_status'] = 1;
    $result = $this->Sales_targets->update_target($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Sales Target 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['month'] = $data2['st.month'] = date('Y-m-01', strtotime($this->security->xss_clean($this->input->post('month'))));
    $data['user_id'] = $data2['st.user_id'] = $this->security->xss_clean($this->input->post('sales_staff'));
    $data['target_type'] = $data2['st.target_type'] = $this->security->xss_clean($this->input->post('sales_target_type_edit'));
    $data['target_id'] = $data2['st.target_id!='] = $this->security->xss_clean($this->input->post('sales_target_id'));

    $count = $this->Sales_targets->select_targets('*', $data2)->num_rows();
    if ($count == 0) {

      $result = $this->Sales_targets->update_target($data);

      $items_array = $newArrayterms = array();
      if ($this->input->post('items')) {
        $items_array = $this->input->post('items');
      }
      $items_array_array_length = sizeof($items_array);
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key => $value) {
          $newArrayterms[$key][$fieldKey] = $value;
        }
      }

      $removed_ids = explode(',', $this->security->xss_clean($this->input->post('sales_target_delete_ids')));
      // exit(print_r($removed_ids));
      foreach ($removed_ids as $key => $id) {
        $item['id'] = $id;
        $item['delete_status'] = 1;
        $this->Sales_targets->update_target_item($item);
      }

      // exit(print_r($newArrayterms));
      foreach ($newArrayterms as $key => $item) {
        $item['target_id'] = $data['target_id'];
        if (empty($item['id'])) {
          $this->Sales_targets->insert_target_item($item);
        } elseif (!in_array($item['id'], $removed_ids)) {
          $this->Sales_targets->update_target_item($item);
        }
      }





      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = 'Sales Target Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Already added !';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Duplicate !!';
    }

    echo (json_encode($flash_data));
  }
}
