<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Stylists extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->loggedIn) {
            $this->session->set_userdata('requested_page', $this->uri->uri_string());
            $this->sma->md('login');
        }
        if (!$this->Owner) {
            $this->session->set_flashdata('warning', lang('access_denied'));
            redirect($_SERVER['HTTP_REFERER']);
        }
        $this->lang->admin_load('stylists', $this->Settings->user_language);
        $this->load->library('form_validation');
        $this->load->admin_model('companies_model');
    }

    public function add()
    {
        $this->sma->checkPermissions(false, true);

        $this->form_validation->set_rules('email', $this->lang->line('email_address'), 'is_unique[companies.email]');

        //this is commented because form validation is not implemented
        // if ($this->form_validation->run('companies/add') == true) {
            $data = [
                'first_name'            => $this->input->post('first_name'),
                'last_name'             => $this->input->post('last_name'),
                'image'                 => $this->input->post('image'),
                'phone'                 => $this->input->post('phone'),
                'email'                 => $this->input->post('email'),
                'address'               => $this->input->post('address'),
                'friend_name'           => $this->input->post('friend_name'),
                'friend_address'        => $this->input->post('friend_address'),
                'friend_phone'          => $this->input->post('friend_phone'),
                'commission_percentage' => $this->input->post('commission_percentage'),
            ];
        // } elseif ($this->input->post('add_biller')) {
        //     $this->session->set_flashdata('error', validation_errors());
        //     admin_redirect('billers');
        // }
        // $this->form_validation->run() == true && 
        if ($this->form_validation->run() == true && $this->companies_model->addStylist($data)) {
            $this->session->set_flashdata('message', $this->lang->line('stylist_added'));
            admin_redirect('stylists');
        } else {
            $this->data['logos']    = $this->getLogoList();
            $this->data['error']    = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['modal_js'] = $this->site->modal_js();
            $this->load->view($this->theme . 'stylists/add', $this->data);
        }
    }

    public function biller_actions()
    {
        if (!$this->Owner && !$this->GP['bulk_actions']) {
            $this->session->set_flashdata('warning', lang('access_denied'));
            redirect($_SERVER['HTTP_REFERER']);
        }

        $this->form_validation->set_rules('form_action', lang('form_action'), 'required');

        if ($this->form_validation->run() == true) {
            if (!empty($_POST['val'])) {
                if ($this->input->post('form_action') == 'delete') {
                    $this->sma->checkPermissions('delete');
                    $error = false;
                    foreach ($_POST['val'] as $id) {
                        if (!$this->companies_model->deleteStylist($id)) {
                            $error = true;
                        }
                    }
                    if ($error) {
                        $this->session->set_flashdata('warning', lang('stylists_x_deleted'));
                    } else {
                        $this->session->set_flashdata('message', $this->lang->line('stylists_deleted'));
                    }
                    redirect($_SERVER['HTTP_REFERER']);
                }

                if ($this->input->post('form_action') == 'export_excel') {
                    $this->load->library('excel');
                    $this->excel->setActiveSheetIndex(0);
                    $this->excel->getActiveSheet()->setTitle(lang('stylists'));
                    $this->excel->getActiveSheet()->SetCellValue('A1', lang('first_name'));
                    $this->excel->getActiveSheet()->SetCellValue('B1', lang('last_name'));
                    $this->excel->getActiveSheet()->SetCellValue('C1', lang('image'));
                    $this->excel->getActiveSheet()->SetCellValue('D1', lang('phone'));
                    $this->excel->getActiveSheet()->SetCellValue('E1', lang('email'));
                    $this->excel->getActiveSheet()->SetCellValue('F1', lang('address'));
                    $this->excel->getActiveSheet()->SetCellValue('G1', lang('friend_name'));
                    $this->excel->getActiveSheet()->SetCellValue('I1', lang('friend_address'));
                    $this->excel->getActiveSheet()->SetCellValue('H1', lang('friend_phone'));
                    $this->excel->getActiveSheet()->SetCellValue('J1', lang('commission_percentage'));

                    $row = 2;
                    foreach ($_POST['val'] as $id) {
                        // $stylist_in_excel = $this->site->getStylistByID($id);

                        $stylist_in_excel = $this->companies_model->getStylistByID($id);
                        $this->excel->getActiveSheet()->SetCellValue('A' . $row, $stylist_in_excel->first_name);
                        $this->excel->getActiveSheet()->SetCellValue('B' . $row, $stylist_in_excel->last_name);
                        $this->excel->getActiveSheet()->SetCellValue('C' . $row, $stylist_in_excel->image);
                        $this->excel->getActiveSheet()->SetCellValue('D' . $row, $stylist_in_excel->phone);
                        $this->excel->getActiveSheet()->SetCellValue('E' . $row, $stylist_in_excel->email);
                        $this->excel->getActiveSheet()->SetCellValue('F' . $row, $stylist_in_excel->address);
                        $this->excel->getActiveSheet()->SetCellValue('G' . $row, $stylist_in_excel->friend_name);
                        $this->excel->getActiveSheet()->SetCellValue('I' . $row, $stylist_in_excel->friend_address);
                        $this->excel->getActiveSheet()->SetCellValue('H' . $row, $stylist_in_excel->friend_phone);
                        $this->excel->getActiveSheet()->SetCellValue('J' . $row, $stylist_in_excel->commission_percentage);
                        $row++;
                    }

                    $this->excel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
                    $this->excel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
                    $this->excel->getDefaultStyle()->getAlignment()->setVertical('center');
                    $filename = 'stylists_' . date('Y_m_d_H_i_s');
                    $this->load->helper('excel');
                    create_excel($this->excel, $filename);
                }
            } else {
                $this->session->set_flashdata('error', $this->lang->line('no_stylist_selected'));
                redirect($_SERVER['HTTP_REFERER']);
            }
        } else {
            $this->session->set_flashdata('error', validation_errors());
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    public function delete($id = null)
    {
        $this->sma->checkPermissions(null, true);

        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }
        if (!$id) {
            $this->sma->send_json(['error' => 1, 'msg' => lang('id_not_found')]);
        }

        if ($this->companies_model->deleteStylist($id)) {
            $this->sma->send_json(['error' => 0, 'msg' => lang('stylist_deleted')]);
        } else {
            $this->sma->send_json(['error' => 1, 'msg' => lang('stylist_x_deleted')]);
        }
    }

    public function edit($id = null)
    {
        $this->sma->checkPermissions(false, true);

        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }

        $stylist_details = $this->companies_model->getStylistByID($id);
        if ($this->input->post('email') != $stylist_details->email) {
            $this->form_validation->set_rules('code', lang('email_address'), 'is_unique[companies.email]');
        }
        
        //this is commented because form validation is not implemented
        if ($this->form_validation->run('stylists/add') == true) {
            $data = [
                'first_name'            => $this->input->post('first_name'),
                'last_name'             => $this->input->post('last_name'),
                'image'                 => $this->input->post('image'),
                'phone'                 => $this->input->post('phone'),
                'email'                 => $this->input->post('email'),
                'address'               => $this->input->post('address'),
                'friend_name'           => $this->input->post('friend_name'),
                'friend_phone'          => $this->input->post('friend_phone'),
                'friend_address'        => $this->input->post('friend_address'),
                'commission_percentage' => $this->input->post('commission_percentage'),
            ];
        } elseif ($this->input->post('edit_stylist')) {
            $this->session->set_flashdata('error', validation_errors());
            admin_redirect('stylists');
        }

        if ($this->form_validation->run() == true && $this->companies_model->updateStylist($id, $data)) {
            $this->session->set_flashdata('message', $this->lang->line('stylist_updated'));
            admin_redirect('stylists');
        } else {
            $this->data['stylist']   = $stylist_details;
            $this->data['error']    = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['logos']    = $this->getLogoList();
            $this->data['modal_js'] = $this->site->modal_js();
            $this->load->view($this->theme . 'stylists/edit', $this->data);
        }
    }

    public function getBiller($id = null)
    {
        $this->sma->checkPermissions('index');

        $row = $this->companies_model->getCompanyByID($id);
        $this->sma->send_json([['id' => $row->id, 'text' => $row->company]]);
    }

    public function getStylists()
    {
        $this->sma->checkPermissions('index');

        // ->select('id, company, name, vat_no, phone, email, city, country')
        
        $this->load->library('datatables');
        $this->datatables
            ->select('id, first_name, last_name, image, phone, email, address, friend_name, friend_address, friend_phone, commission_percentage')
            ->from('stylists')
            // ->add_column('Actions', "<div class=\"text-center\"><a class=\"tip\" title='" . $this->lang->line('edit_stylist') . "' href='#' data-toggle='modal' data-target='#myModal'><i class=\"fa fa-edit\"></i></a> <a href='#' class='tip po' title='<b>" . $this->lang->line('delete_stylist') . "</b>' data-content=\"<p>" . lang('r_u_sure') . "</p><a class='btn btn-danger po-delete' href='" . admin_url('stylists/delete/$1') . "'>" . lang('i_m_sure') . "</a> <button class='btn po-close'>" . lang('no') . "</button>\"  rel='popover'><i class=\"fa fa-trash-o\"></i></a></div>", 'id');
            ->add_column('Actions', "<div class=\"text-center\"><a class=\"tip\" title='" . $this->lang->line('edit_stylist') . "' href='" . admin_url('stylists/edit/$1') . "' data-toggle='modal' data-target='#myModal'><i class=\"fa fa-edit\"></i></a> <a href='#' class='tip po' title='<b>" . $this->lang->line('delete_stylist') . "</b>' data-content=\"<p>" . lang('r_u_sure') . "</p><a class='btn btn-danger po-delete' href='" . admin_url('stylists/delete/$1') . "'>" . lang('i_m_sure') . "</a> <button class='btn po-close'>" . lang('no') . "</button>\"  rel='popover'><i class=\"fa fa-trash-o\"></i></a></div>", 'id');
            //this add_column has href as #
        //->unset_column('id');
        
        //original:  ->add_column('Actions', "<div class=\"text-center\"><a class=\"tip\" title='" . $this->lang->line('edit_stylist') . "' href='" . admin_url('stylists/edit/$1') . "' data-toggle='modal' data-target='#myModal'><i class=\"fa fa-edit\"></i></a> <a href='#' class='tip po' title='<b>" . $this->lang->line('delete_stylist') . "</b>' data-content=\"<p>" . lang('r_u_sure') . "</p><a class='btn btn-danger po-delete' href='" . admin_url('stylists/delete/$1') . "'>" . lang('i_m_sure') . "</a> <button class='btn po-close'>" . lang('no') . "</button>\"  rel='popover'><i class=\"fa fa-trash-o\"></i></a></div>", 'id');

        echo $this->datatables->generate();
    }

    public function getLogoList()
    {
        $this->load->helper('directory');
        $dirname = 'assets/uploads/logos';
        $ext     = ['jpg', 'png', 'jpeg', 'gif'];
        $files   = [];
        if ($handle = opendir($dirname)) {
            while (false !== ($file = readdir($handle))) {
                for ($i = 0; $i < sizeof($ext); $i++) {
                    if (stristr($file, '.' . $ext[$i])) { //NOT case sensitive: OK with JpeG, JPG, ecc.
                        $files[] = $file;
                    }
                }
            }
            closedir($handle);
        }
        sort($files);
        return $files;
    }

    public function index($action = null)
    {
        $this->sma->checkPermissions();

        $this->data['error']  = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
        $this->data['action'] = $action;
        $bc                   = [['link' => base_url(), 'page' => lang('home')], ['link' => '#', 'page' => lang('stylists')]];
        $meta                 = ['page_title' => lang('stylists'), 'bc' => $bc];
        $this->page_construct('stylists/index', $meta, $this->data);
    }

    public function suggestions($term = null, $limit = null)
    {
        $this->sma->checkPermissions('index');

        if ($this->input->get('term')) {
            $term = $this->input->get('term', true);
        }
        $term            = addslashes($term);
        $limit           = $this->input->get('limit', true);
        $rows['results'] = $this->companies_model->getBillerSuggestions($term, $limit);
        $this->sma->send_json($rows);
    }
}