<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Branches 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('Branches_model', 'Branches');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Attendance_model', 'Attendance');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Settings_model', 'Settings');

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

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

    if ($this->session->userdata('branch_id')!=0) {
      redirect(base_url(), 'refresh');
    }

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

  public function view()
  {
    // Check Module is Enabled or Not
    $this->page_data['page_name'] = 'branches_view';
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['tax_state_codes'] = $this->Settings->select_tax_state_codes("*")->result();
    $this->page_data['users'] = $this->User->select_user("", "")->result();
    $this->load->view('Index', $this->page_data);
  }

  public function select_branches($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'];
    }

    $result    = $this->Branches->select_branches("*", $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) :

      if ($row->branch_active_status == 1) {
        $branch_active_status = '<button type="button" class="btn btn-sm btn-success">Active</button>';
      } else {
        $branch_active_status = '<button type="button" class="btn btn-sm btn-danger">In-active</button>';
      }
      $btn_edit = $btn_delete = '';
      if ($this->session->userdata('user_role') == 'admin') {

        // $btn_edit = '<a onclick="$(\'#visible_status_edit\').bootstrapSwitch(\'state\', true, true);" style="margin-left: 5px;margin-right: 5px" id="branch_edit_btn" href="#branch_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="branch_delete_btn" href="#branch_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>';
      }
      if ($this->session->userdata('user_role') == 'admin') {

        $sl_no++;
        $array[$j][] = $sl_no;
        $array[$j][] = $row->branch_name;
        $array[$j][] = $row->branch_email;
        $array[$j][] = $row->branch_phone;
        $array[$j][] = $this->config->item('Material_sale_price'.$row->sale_price_category.'_name');
        $array[$j][] = $row->quotation_prefix;
        $array[$j][] = $row->workorder_prefix;
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/branches/' . $row->branch_logo . '" ><img src="' . base_url() . 'uploads/branches/' . $row->branch_logo . '" style="width:100px"/></a>';
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/quotation_workorder/' . $row->quotation_header . '" ><img src="' . base_url() . 'uploads/quotation_workorder/' . $row->quotation_header . '" style="width:100px"/></a>';
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/quotation_workorder/' . $row->quotation_footer . '" ><img src="' . base_url() . 'uploads/quotation_workorder/' . $row->quotation_footer . '" style="width:100px"/></a>';
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_header . '" ><img src="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_header . '" style="width:100px"/></a>';
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_logo . '" ><img src="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_logo . '" style="width:100px"/></a>';
        $array[$j][] = '<a target="_blank"  style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_footer . '" ><img src="' . base_url() . 'uploads/quotation_workorder/' . $row->workorder_footer . '" style="width:100px"/></a>';
        $array[$j][] = $row->branch_address;
        $array[$j][] = $row->branch_taxno;
        $array[$j][] = $row->state_name."-".$row->state_code;
        $array[$j][] = $branch_active_status;
        $array[$j][] = $btn_edit . $btn_delete;
        $array[$j][] = $row->branch_id;
        $array[$j][] = $row->branch_active_status;
        $array[$j][] = $row->branch_logo;

      }
      $j++;
    endforeach;

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

  public function create()
  {
    $data['branch_email'] = $this->security->xss_clean($this->input->post('email'));
    $data['branch_name'] = $this->security->xss_clean($this->input->post('name'));
    $this->db->where('(branch_email="'.$data['branch_email'].'" or branch_name="'.$data['branch_name'].'")');
    $count = $this->Branches->select_branches('*')->num_rows();

    if ($count == 0) {
      $data['quotation_prefix'] = $this->security->xss_clean($this->input->post('quotation_prefix'));
      $data['workorder_prefix'] = $this->security->xss_clean($this->input->post('workorder_prefix'));
      $data['branch_address'] = $this->security->xss_clean($this->input->post('address'));
      $data['branch_taxno'] = $this->security->xss_clean($this->input->post('taxno'));
      $data['tax_state_id'] = $this->security->xss_clean($this->input->post('state_id'));
      $data['sale_price_category'] = $this->security->xss_clean($this->input->post('sale_price_category'));
      $data['branch_phone'] = $this->security->xss_clean($this->input->post('phone'));

      $file_error = 0;
      if ($file_error == 0) {
        $status = $this->security->xss_clean($this->input->post('status'));
        if ($status == 'on') {
          $data['branch_active_status'] = 1;
        } else {
          $data['branch_active_status'] = 0;
        }

        $result2 = $this->Branches->create_branch($data);
        $flash_data['status'] = $result2['status'];
        if ($result2['status'] == 1) {

          $branch_id_inserted = $result2['insert_id'];

          // create Branch Admin
          $data2['branch_id'] = $branch_id_inserted;
          $data2['user_role'] = 2;
          $data2['acc_status'] = 1;
          $data2['phone_no'] = $data['branch_phone'];
          $data2['user_alias'] = $data['branch_name']." Branch Admin";
          $data2['user_designation'] = "Branch Admin";
          $data2['username'] = $data['branch_email'];
          $data2['created_date'] = date('Y-m-d H:i:s');
          function generate_password($length = 6)
          {
            $chars = "123456789";
            $password = substr(str_shuffle($chars), 0, $length);
            return $password;
          }
          $data2['password'] = generate_password();
          $result3 = $this->User->insert_user($data2);

          // create warehouse for branch
          $warehouse_data['location_branch_id'] = $branch_id_inserted;
          $warehouse_data['location_type'] = 'ware_house';
          $warehouse_data['location_name'] = $data['branch_name'] . " Warehouse";
          $warehouse_data['editable_status'] = 0;
          $result4 = $this->Stock->insert_stock_location($warehouse_data);

          $data2['login_id'] = $result3['insert_id'];
          $flash_data['flashdata_type'] = 'success';
          $flash_data['flashdata_msg'] = 'Branch Added Succesfully';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          $email_status = $this->send_email($result3['insert_id'], "activation");
          $flash_data['flashdata_msg'] .= '<br/>Branch Admin Account Created Successfully!.';
          if ($email_status == 1) {
            $flash_data['flashdata_msg'] .= " & Email With Account Credentials Sent Successfully";
          } else {
            $flash_data['flashdata_msg'] .= "<strong> & Email With Account Credentials Sending Failed!!</strong>";
          }

          ##storing Email Sent Status
          $data5['email_sent_status'] = $email_status;
          $data5['user_id'] =  $data2['login_id'];
          // Load the model
          $result5 = $this->User->update_user($data5);

          // Create Employee A/C
          $employee_data['branch_id'] = $branch_id_inserted;
          $employee_data['user_id'] = $data2['login_id'];
          $employee_data['employee_name'] = $data2['user_alias'];
          $employee_data['user_designation'] = $data2['user_designation'];
          $employee_data['phone_no'] = $data['branch_phone'];
          $employee_data['created_by'] = $this->session->userdata('user_id');
          $employee_data['created_date'] = date('Y-m-d H:i:s');
          $employee_result = $this->Employee->create_employee($employee_data);

          // CReate Account Head
          $account_data['acc_head_name'] = $data2['user_alias'] . "'s Account";
          $account_data['acc_head_branch_id'] = $branch_id_inserted;
          $account_data['account_type'] = 32; //Cash Account
          $account_data['acc_user_id'] = $data2['login_id'];
          $account_data['acc_employee_id'] = $employee_result['insert_id'];
          $account_data['head_editable'] = 0;
          $account_data['op_balance'] = 0;
          $account_data['created_date'] = date('Y-m-d H:i:s');
          $account_data['created_by'] = $this->session->userdata('user_id');
          $account_result = $this->Account->create_account_head($account_data);

          if (isset($_FILES['branch_logo']) && $_FILES['branch_logo']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['branch_logo']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config['upload_path']   = 'uploads/branches/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            // $config['max_size']      = 3000;
            $config['file_name'] = "logo_branch_".$branch_id_inserted.".png";
            $this->load->library('upload', $config,'branch_logo');
            $this->branch_logo->initialize($config);
            $upload_branch_logo = $this->branch_logo->do_upload('branch_logo');
            $branch_update_data['branch_logo'] = $config['file_name'];
          }


          if (isset($_FILES['quotation_header']) && $_FILES['quotation_header']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['quotation_header']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config2['upload_path']   = 'uploads/quotation_workorder/';
            $config2['allowed_types'] = 'jpg|jpeg|png';
            // $config2['max_size']      = 3000;
            $config2['file_name'] = 'quotation_header_branch_'.$branch_id_inserted.".jpg";
            $this->load->library('upload', $config2,'quotation_header');
            $this->quotation_header->initialize($config2);
            $upload_quotation_header = $this->quotation_header->do_upload('quotation_header');
            $branch_update_data['quotation_header'] = $config2['file_name'];
          }

          if (isset($_FILES['quotation_footer']) && $_FILES['quotation_footer']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['quotation_footer']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config2['upload_path']   = 'uploads/quotation_workorder/';
            $config2['allowed_types'] = 'jpg|jpeg|png';
            // $config2['max_size']      = 3000;
            $config2['file_name'] = 'quotation_footer_branch_'.$branch_id_inserted.".jpg";
            $this->load->library('upload', $config2,'quotation_footer');
            $this->quotation_footer->initialize($config2);
            $upload_quotation_footer = $this->quotation_footer->do_upload('quotation_footer');
            $branch_update_data['quotation_footer'] = $config2['file_name'];
          }

          if (isset($_FILES['workorder_header']) && $_FILES['workorder_header']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['workorder_header']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config2['upload_path']   = 'uploads/quotation_workorder/';
            $config2['allowed_types'] = 'jpg|jpeg|png';
            // $config2['max_size']      = 3000;
            $config2['file_name'] = 'workorder_header_branch_'.$branch_id_inserted.".jpg";
            $this->load->library('upload', $config2,'workorder_header');
            $this->workorder_header->initialize($config2);
            $upload_workorder_header = $this->workorder_header->do_upload('workorder_header');
            $branch_update_data['workorder_header'] = $config2['file_name'];
          }

          if (isset($_FILES['workorder_logo']) && $_FILES['workorder_logo']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['workorder_logo']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config2['upload_path']   = 'uploads/quotation_workorder/';
            $config2['allowed_types'] = 'jpg|jpeg|png';
            // $config2['max_size']      = 3000;
            $config2['file_name'] = 'workorder_logo_branch_'.$branch_id_inserted.".jpg";
            $this->load->library('upload', $config2,'workorder_logo');
            $this->workorder_logo->initialize($config2);
            $upload_workorder_logo = $this->workorder_logo->do_upload('workorder_logo');
            $branch_update_data['workorder_logo'] = $config2['file_name'];
          }

          if (isset($_FILES['workorder_footer']) && $_FILES['workorder_footer']["size"] > 0) {
            //          Check Blacklist Extensions
            $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
            foreach ($blacklist as $item) {
              if (preg_match("/$item\$/i", $_FILES['workorder_footer']['name'])) {
                $file_error = 1;
              }
            }

            if ($file_error == 1) {
              $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
              $flash_data['flashdata_type'] = 'error';
              $flash_data['alert_type'] = 'danger';
              $flash_data['flashdata_title'] = 'File Format Error !!';
            }

            //      File Upload
            $config2['upload_path']   = 'uploads/quotation_workorder/';
            $config2['allowed_types'] = 'jpg|jpeg|png';
            // $config2['max_size']      = 3000;
            $config2['file_name'] = 'workorder_footer_branch_'.$branch_id_inserted.".jpg";
            $this->load->library('upload', $config2,'workorder_footer');
            $this->workorder_footer->initialize($config2);
            $upload_workorder_footer = $this->workorder_footer->do_upload('workorder_footer');
            $branch_update_data['workorder_footer'] = $config2['file_name'];
          }

          $branch_update_data['branch_id'] = $branch_id_inserted;
          $this->Branches->update_branch($branch_update_data);
        } 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'] = 'Branch Already Exists with Same Email/Name';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }


    echo json_encode($flash_data);
  }

  public function update()
  {

    $data['branch_name'] = $data_check['branch_name'] = $this->security->xss_clean($this->input->post('name'));
    $data['branch_email'] = $data_check['branch_name'] = $this->security->xss_clean($this->input->post('email'));
    $data['branch_id'] = $data_check['branch_id!='] = $this->security->xss_clean($this->input->post('branch_id'));

    $count = $this->Branches->select_branches('*', $data_check)->num_rows();

    if ($count == 0) {

      $file_error = 0;

      if (isset($_FILES['branch_logo']) && $_FILES['branch_logo']["size"] > 0) {
        //          Check Blacklist Extensions
        $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
        foreach ($blacklist as $item) {
          if (preg_match("/$item\$/i", $_FILES['branch_logo']['name'])) {
            $file_error = 1;
          }
        }

        if ($file_error == 1) {
          $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'File Format Error !!';
        }

        //      File Upload
        $config['upload_path']   = 'uploads/branches/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        // $config['max_size']      = 3000;
        // $config['max_width']     = 1980;
        // $config['max_height']    = 1080;
        $config['encrypt_name']    = TRUE;
        // $config['file_name'] = date('YmdHis');
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('branch_logo')) {
          $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();
          $data['branch_logo'] = $file_data['file_name'];
        }
      }

      if ($file_error == 0) {

        $status = $this->security->xss_clean($this->input->post('status'));
        if ($status == 'on') {
          $data['branch_active_status'] = 1;
        } else {
          $data['branch_active_status'] = 0;
        }

        $result2 = $this->Branches->update_branch($data);
        $flash_data['status'] = $result2;
        if ($result2 == 1) {

          $branch_id_inserted = $data['branch_id'];

          // update admin user for branch
          $branch_admin = $this->User->select_user('*', array('user_role' => 2, 'branch_id' => $branch_id_inserted))->result();
          foreach ($branch_admin  as $key => $value) {
            $data2['user_alias'] = $data['branch_name']." Branch Admin";
            $data2['username'] = $data['branch_email'];
            $data2['user_id'] = $value->user_id;
            $result3 = $this->User->update_user($data2);

            $employee_data = $this->Employee->select_employee("e.*", array("e.user_id" => $value->user_id));
            if ($employee_data->num_rows() == 1) {
              $employee_data = $employee_data->row();
              // Update Employee A/C
              $employee_update_data['employee_id'] = $employee_data->employee_id;
              $employee_update_data['employee_name'] = $data2['user_alias'];
              $employee_update_data['updated_by'] = $this->session->userdata('user_id');
              $employee_update_data['updated_date'] = date('Y-m-d H:i:s');
              $employee_result = $this->Employee->update_employee($employee_update_data);

              $account_head_data = $this->Account->select_account_heads("", array("acc_employee_id" => $employee_data->employee_id));
              if ($account_head_data->num_rows() == 1) {
                // Update Account Head
                $account_data['acc_head_name'] = $data2['user_alias'] . "'s Account";
                $account_data['acc_head_id'] = $account_head_data->row()->acc_head_id;
                $account_data['updated_date'] = date('Y-m-d H:i:s');
                $account_data['updated_by'] = $this->session->userdata('user_id');
                $account_result = $this->Account->update_account_head($account_data);
              }
            }
          }

          // update warehouse for branch
          $stock_location = $this->Stock->select_stock_locations('*', array('location_branch_id' => $branch_id_inserted, 'location_type' => 'ware_house'));
          if($stock_location->num_rows()==1){
            $warehouse_data['location_id'] = $stock_location->row()->location_id;
            $warehouse_data['location_name'] = $data['branch_name']." Warehouse";
            $result3 = $this->Stock->update_stock_location($warehouse_data);
          }

          $flash_data['flashdata_type'] = 'success';
          $flash_data['flashdata_msg'] = 'Branch Update 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'] = 'Branch Already Exists';
      $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['branch_id'] = $this->security->xss_clean($this->input->post('branch_id'));
    $data2['delete_status'] = 1;
    $result2 = $this->Branches->update_branch($data2);

    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Branch 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 send_email($user_id, $email_type)
  {

    if ($email_type == 'activation') {
      $result  = $this->User->select_user("", array("user_id" => $user_id));
      if ($result->num_rows() == 1) {
        ##Send Mail
        $password = $result->row()->password;
        $email = $result->row()->username;
        $user_name = $result->row()->user_alias;
        $data5['subject'] = "Account Activation in " . $this->config->item('company_name') . " Application";
        $message = file_get_contents(base_url() . 'template/email/welcome.html');
        $message = str_replace("#username", $user_name, $message);
        $message = str_replace("#email", $email, $message);
        $message = str_replace("#password", $password, $message);
        $message = str_replace("#url", base_url() . "template/email", $message);
        $message = str_replace("#login_link", base_url() . "", $message);
        $data5['message'] = $message;
        $data5['to'] = $email;
        $result4 = $this->User->send_email($data5);
        if ($result4 == 1) {
          return 1;
        } else {
          return 0;
        }
      } else {
        return 0;
      }
    } else {
      return 0;
    }
  }

  public function select_details(){
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['branch_id'] = $_POST['id'];
    }
    $result	= $this->Branches->select_branches("",$data);
    if($result->num_rows()==1) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->row()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function profile($id = "")
  {
    if ($id != "") {
      // if branch exists the show page else show_404
      $result = $this->Branches->select_branches("", array("branch_id" => $id));
      if($result->num_rows()==1){

        $this->page_data['branch_data'] = $result->row();
        $this->page_data['page_name'] = "branch_profile";
        $this->load->view('Index', $this->page_data);


      }else{
        show_404();
      }
    } else {
      show_404();
    }
  }
}
