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

/**
 * 
 * Controller pentru gestionarea client
 * 
 */
class Client extends MY_Controller{
    
    function __construct() 
    {
        parent::__construct();
        $this->load->model('client_model');
        $this->load->library('login_library');
    }

    /**
     * 
     * Metoda pentru afisarea paginii Clienti.
     * 
     * 
     */
    function index()
    {
        $data['title'] = "Lista clienti";

        //jqgrid item
        $client         = 'Client';
        $responsabil    = 'Responsabil';
        $email          = 'Email';
        $activ          = 'Activ';
        $data_adaugare  = 'Data adaugare';
        $optiuni        = 'Optiuni';
 
        $colModel_Items = "[
                        {name:'I.denumire',index:'I.denumire',  groupOp:'and', width:100, align:'left'},
                        {name:'I.responsabil',index:'I.responsabil',  groupOp:'and', width:100, align:'left'},
                        {name:'I.email',index:'I.email',  groupOp:'and', width:'100', align:'left'},
                        {name:'I.data_adaugare',index:'I.data_adaugare',  groupOp:'and', width:'100', align:'center'},
                        {name:'I.activ',index:'I.activ',  groupOp:'and', width:'50', align:'center'},
                        {name:'optiune',index:'optiune', width:100, editCell: false, search: false, align:'center', sortable:false,editable:false} 
                  ]";

        $colNames_Items = "['".$client."', '".$responsabil."',  '".$email."','".$data_adaugare."','".$activ."','".$optiuni."']";
        
        $data['colModel'] = $colModel_Items;
        $data['colNames'] = $colNames_Items;
        
        $this->load->view('admin/client/lista_inregistrari', $data);
    }
    
    // load clienti
    function loadData()
    {
            $page = isset($_POST['page'])?$_POST['page']:1; 
            $limit = isset($_POST['rows'])?$_POST['rows']:10; 
            $sidx = isset($_POST['sidx'])?$_POST['sidx']:'denumire'; 
            $sord = isset($_POST['sord'])?$_POST['sord']:'';         
            $start = $limit*$page - $limit; 
            $start = ($start<0)?0:$start; 
            $responce = (object)array();
            $where = " 1 "; 
            
            $searchField = isset($_POST['searchField']) ? $_POST['searchField'] : false;
            $searchOper = isset($_POST['searchOper']) ? $_POST['searchOper']: false;
            $searchString = isset($_POST['searchString']) ? $_POST['searchString'] : false;
            
            $ops_array = array(
                'eq'=>'=', 
                'ne'=>'<>',
                'lt'=>'<', 
                'le'=>'<=',
                'gt'=>'>', 
                'ge'=>'>=',
                'bw'=>'LIKE',
                'bn'=>'NOT LIKE',
                'in'=>'LIKE', 
                'ni'=>'NOT LIKE', 
                'ew'=>'LIKE', 
                'en'=>'NOT LIKE', 
                'in'=>'LIKE', 
                'ni'=>'NOT LIKE', 
                'ew'=>'LIKE', 
                'en'=>'NOT LIKE', 
                'cn'=>'LIKE', 
                'nc'=>'NOT LIKE' 
                );
            
            if ($_POST['_search'] == 'true') {
                
                if(isset($searchField) && $searchString)
                {
            
                foreach ($ops_array as $key=>$value){
                    if ($searchOper==$key) {
                        $ops = $value;
                    }
                }
                if($searchOper == 'eq' ) $searchString = $searchString;
                if($searchOper == 'bw' || $searchOper == 'bn') $searchString .= '%';
                if($searchOper == 'ew' || $searchOper == 'en' ) $searchString = '%'.$searchString;
                if($searchOper == 'cn' || $searchOper == 'nc' || $searchOper == 'in' || $searchOper == 'ni') $searchString = '%'.$searchString.'%';

                $where = "$searchField $ops '$searchString' ";
                }
                
                $filters = json_decode($this->input->post('filters'), true);  
                $groupOp = $filters['groupOp'];  
                if(isset($filters))
                {
                    $where = ' 1 ';
                    $ops1  = ' AND ';
                    foreach ( $filters['rules'] as $item){ 
                        $searchField = $item['field'];
                        $searchOper = $item['op'];
                        $searchString = $item['data'];
                        
                        foreach ($ops_array as $key=>$value){
                            if ($searchOper==$key) {
                                $ops1 = $value;
                            }
                        }
                        if ($searchOper == 'eq')
                            $searchString = $searchString;
                        if ($searchOper == 'bw' || $searchOper == 'bn')
                            $searchString .= '%';
                        if ($searchOper == 'ew' || $searchOper == 'en')
                            $searchString = '%' . $searchString;
                        if ($searchOper == 'cn' || $searchOper == 'nc' || $searchOper == 'in' || $searchOper == 'ni')
                            $searchString = '%' . $searchString . '%';
                        
                        $where .= $groupOp." $searchField $ops1 '$searchString' ";
                    }
                }

            }

            if(!$sidx) 
                $sidx =1;
            
            $all_results = $this->client_model->getAllData();
            $count = ($all_results)?count($all_results):0;  
            
            if( $count > 0 ) {
                $total_pages = ceil($count/$limit);    
            } else {
                $total_pages = 0;
            }

            if ($page > $total_pages) 
                $page=$total_pages;
            
            $base = base_url();
            
            $query = $this->client_model->getAllData($start,$limit,$sidx,$sord,$where); 
            
            $responce->page = $page;
            $responce->total = $total_pages;
            $responce->records = $count;
            $i=0;
            $c=1;
            if(isset($query) && $query)
                foreach($query as $row) {
                  
                $client         = $row->denumire;
                $email          = $row->email;
                $responsabil    = $row->responsabil;

                $activ          = (isset($row->activ) && $row->activ>0) ? "<i class='fa fa-circle'></i>" : "<i class='fa fa-circle-o'></i>";

                $data_adaugare  = $row->data_adaugare;

                $change = "<a title='Activ/Dezactiv' onclick='chg($row->id_client,$row->activ);' class='btn btn-warning'><i class='fa fa-refresh'></i></a>";

                $delete = "<a title='Delete' onclick='deleteClient($row->id_client);' class='btn btn-danger'><i class='fa fa-times'></i></a>";
                
                $url_e  = base_url()."adm/client/edit/".$row->id_client;
                $edit   = "<a title='Modifica' href='$url_e' class='btn btn-success'><i class='fa fa-pencil-square-o'></i></a>";

                $optiuni = $change."&nbsp;".$edit."&nbsp;".$delete;

                
                $responce->rows[$i]['id_client']=$row->id_client;
                $responce->rows[$i]['cell']=array($client, $responsabil, $email, $data_adaugare, $activ, $optiuni);
                $i++;
                $c++;
            }

        echo json_encode($responce);
    }
    
    function add()
    {
        $data['title'] = "Adauga Client";
        
        $denumire      = $this->input->post('denumire');
        if(isset($denumire) && $denumire)
        {
            $id_utilizator  = $this->login_library->getID();

            $responsabil    = $this->input->post('responsabil');
            $email          = $this->input->post('email');

            $this->db->insert('client',array('denumire' => $denumire, 'id_utilizator' => $id_utilizator, 'responsabil' => $responsabil, 'email' => $email,  'data_adaugare' => date('Y-m-d'), 'activ' => 1));

            $id_client = $this->db->insert_id();

            if(isset($id_client) && $id_client)
            {
                $this->session->set_flashdata('success', 'Inregistrare cu succes!');
                redirect('adm/client?success=true');
            }
            else
            {
                $this->session->set_flashdata('warning', 'Eroare la inregistrare!');
                redirect('adm/client/add?success=false');
            }
        }
        
        $this->load->view('admin/client/add_page', $data);
    }

    function change()
    {
        if (!$this->input->is_ajax_request()) {
            exit('No direct script access allowed');
        }
       
        $id         = $this->input->post('id'); 
        $stare      = $this->input->post('stare'); 
        $opt        = (isset($stare) && $stare>0)? 0 : 1;

        $infoClient     = $this->client_model->getInfoClient($id);
        if(isset($infoClient) && $infoClient)
        {
            $this->db->where('id_client', $id)->update('client', array('activ' => $opt));
        
            echo json_encode($id);
        }
    }

    function edit()
    {
        $id = $this->uri->segment(4);

        $data['title']  = 'Modifica Client';

        if(isset($id) && $id)
        {
            $infoClient = $this->client_model->getInfoClient($id);

            if(isset($infoClient) && $infoClient)
            {

                $data['infoDB'] = $infoClient;

            }
        }
        
        $id_client = $this->input->post('id_client');
        if(isset($id_client) && $id_client)
        {
            
            $denumire       = $this->input->post('denumire');
            $responsabil    = $this->input->post('responsabil');
            $email          = $this->input->post('email');
            
            if(isset($denumire) && $denumire)      
            {         

                $this->db->where('id_client', $id_client)->update('client',array('denumire' => $denumire, 'responsabil' => $responsabil, 'email' => $email));

                $this->session->set_flashdata('success', 'Actualizare cu succes!');
                redirect('adm/client?success=true');
            }
            else
            {
                $this->session->set_flashdata('warning', 'Eroare la inregistrare!');
                redirect('adm/client/edit/'.$id_client.'?success=false');
            }

        }

        $this->load->view('admin/client/edit_page',$data); 
    }

    function delete()
    {
        if (!$this->input->is_ajax_request()) {
            exit('No direct script access allowed');
        }
        
        $id_utilizator  = $this->login_library->getID();
        $id             = $this->input->post('id'); 

        $infoClient     = $this->client_model->getInfoClient($id);
        if(isset($infoClient) && $infoClient)
        {
            $this->db->where('id_client', $id)->delete('client');

            //logs
            $activitate = "Clientul ".$infoClient->denumire." cu id-ul:".$id." a fost eliminat.";
            $this->db->insert('activitate',array('id_utilizator' => $id_utilizator, 'activitate' => $activitate, 'data_adaugare' => date('Y-m-d H:i:s')));
            
            echo json_encode($id);
        }
    }
}