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

/**
 * 
 * Controller pentru gestionarea docs
 * 
 */
class Document extends MY_Controller{
    
    function __construct() 
    {
        parent::__construct();
        $this->load->model('document_model');
        $this->load->library('login_library');
        $this->load->library('global_library');
    }

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

        //jqgrid item
        $doc            = 'Document';
        $cod            = 'Barcode';
        $status         = 'Status';
        $activ          = 'Activ';
        $data_adaugare      = 'Data adaugare';
        $data_modificare    = 'Data modificare';
        
        $stare              = 'Stare';
        $data_stare         = 'Data stare';
        $optiuni            = 'Optiuni';
 
        $colModel_Items = "[
                        {name:'I.denumire',index:'I.denumire',  groupOp:'and', width:100, align:'left'},
                        {name:'I.id_document',index:'I.id_document',  groupOp:'and', width:100, align:'center'},
                        {name:'S.denumire',index:'S.denumire',  groupOp:'and', width:'100', align:'center'},
                        {name:'I.data_adaugare',index:'I.data_adaugare',  groupOp:'and', width:'80', align:'center'},
                        {name:'I.data_modificare',index:'I.data_modificare',  groupOp:'and', width:'80', align:'center'},
                        {name:'SS.denumire',index:'SS.denumire',  groupOp:'and', width:'100', align:'center'},
                        {name:'I.data_stare',index:'I.data_stare',  groupOp:'and', width:'100', align:'center'},
                        {name:'optiune',index:'optiune', width:100, editCell: false, search: false, align:'center', sortable:false,editable:false} 
                  ]";

        $colNames_Items = "['".$doc."', '".$cod."', '".$status."','".$data_adaugare."','".$data_modificare."','".$stare."','".$data_stare."','".$optiuni."']";
        
        $data['colModel'] = $colModel_Items;
        $data['colNames'] = $colNames_Items;
        
        $this->load->view('admin/document/lista_inregistrari', $data);
    }
    
    // load documente
    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->document_model->getAllData();
            $count = count($all_results);  
            
            if( $count > 0 ) {
                $total_pages = ceil($count/$limit);    
            } else {
                $total_pages = 0;
            }

            if ($page > $total_pages) 
                $page=$total_pages;
            
            $base = base_url();
            
            $query = $this->document_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) {
                  
                $doc            = "<span title='$row->descriere'><i class='fa fa-info-circle'></i> ".$row->denumire."</span>";  

                $href_cod       = base_url()."adm/document/barcode/".$row->id_document;
                $cod            = "<a target='_blank' class='btn $row->class' href='$href_cod'><i class='fa fa-barcode'></i> ".$row->id_document."</a>";  

                $list_status    = $this->document_model->getStatus(0);
                $select_status  = $this->global_library->createSelect($list_status, 'id_status', 'denumire', "Select status");
                if($row->status>0)
                    $select_status  = $this->global_library->createAutoSelect($list_status, 'id_status', 'denumire', $row->status, false);

                $list_stare = $this->document_model->getStare();
                $select_stare  = $this->global_library->createSelect($list_stare, 'id_stare', 'denumire', "Select stare");
                if($row->stare>0)
                    $select_stare  = $this->global_library->createAutoSelect($list_stare, 'id_stare', 'denumire', $row->stare, false);

           
                $data_adaugare  = $row->data_adaugare;
                $data_modificare= $row->data_modificare;
                $data_stare     = $row->data_stare;

                $status = $row->sts;
                $stare = "<select id='stare$row->id_document' onchange='chgStare($row->id_document);'>".$select_stare."</select>";

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

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

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

                $responce->rows[$i]['id_document']=$row->id_document;
                $responce->rows[$i]['cell']=array($doc, $cod, $status, $data_adaugare, $data_modificare, $stare, $data_stare, $optiuni);
                $i++;
                $c++;
            }

        echo json_encode($responce);
    }

    function add()
    {
        $data['title'] = "Adauga Document/Dosar";

        $select_status = $this->document_model->getStatus();
        $data['select_status'] = $this->global_library->createSelect($select_status, 'id_status', 'denumire', false);

        $select_stare = $this->document_model->getStare();
        $data['select_stare'] = $this->global_library->createSelect($select_stare, 'id_stare', 'denumire', false);
        
        $denumire      = $this->input->post('denumire');
        if(isset($denumire) && $denumire)
        {
            $id_utilizator  = $this->login_library->getID();

            $descriere      = $this->input->post('descriere');
            
            $stare          = $this->input->post('stare');
            $status         = ($stare>2)?4:3;

            $this->db->insert('document',array('denumire' => $denumire, 'id_utilizator' => $id_utilizator, 'descriere' => $descriere, 'status' => $status, 'stare' => $stare, 'data_adaugare' => date('Y-m-d'), 'activ' => 1));

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

            //initializare in arhiva
            $this->db->insert('client_document',array('id_client' => 0, 'id_document' => $id_document,'id_utilizator' => $id_utilizator, 'denumire' => $denumire, 'descriere' => $descriere, 'observatii' => "Initializare", 'status' => $status, 'data_adaugare' => date('Y-m-d H:i:s'), 'activ' => 1));

            if(isset($id_document) && $id_document)
            {
                $this->session->set_flashdata('success', 'Inregistrare cu succes!');
                redirect('adm/document?success=true');
            }
            else
            {
                $this->session->set_flashdata('warning', 'Eroare la inregistrare!');
                redirect('adm/document/add?success=false');
            }
        }
        
        $this->load->view('admin/document/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;

        $infoDoc     = $this->document_model->getInfoDocument($id);
        if(isset($infoDoc) && $infoDoc)
        {
            $this->db->where('id_document', $id)->update('document', array('activ' => $opt));
        
            echo json_encode($id);
        }
    }

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

        $infoDoc     = $this->document_model->getInfoDocument($id);
        if(isset($infoDoc) && $infoDoc)
        {
            $this->db->where('id_document', $id)->update('document', array('status' => $sel));
        
            echo json_encode($id);
        }
    }

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

        $infoDoc     = $this->document_model->getInfoDocument($id);
        if(isset($infoDoc) && $infoDoc)
        {
            //daca stare topit sau inchis status = blocat
            $status = 1;
            if($sel >2)
                $status = 4;

            $this->db->where('id_document', $id)->update('document', array('stare' => $sel, 'status' => $status, 'data_stare' => date('Y-m-d H:i:s')));

            echo json_encode($id);
        }
    }

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

        $data['title']  = 'Modifica Document/Dosar';

        if(isset($id) && $id)
        {
            $infoDoc = $this->document_model->getInfoDocument($id);

            if(isset($infoDoc) && $infoDoc)
            {
                $data['infoDB'] = $infoDoc;
            }
        }
        
        $id_document = $this->input->post('id_document');
        if(isset($id_document) && $id_document)
        {
            $denumire     = $this->input->post('denumire');
            $descriere    = $this->input->post('descriere');
            
            if(isset($denumire) && $denumire)      
            {         
                $this->db->where('id_document', $id_document)->update('document',array('denumire' => $denumire, 'descriere' => $descriere, 'data_modificare' => date('Y-m-d')));

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

        }

        $this->load->view('admin/document/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'); 

        $infoDoc     = $this->document_model->getInfoDocument($id);
        if(isset($infoDoc) && $infoDoc)
        {
            $this->db->where('id_document', $id)->delete('document');

            //logs
            $activitate = "Documentul ".$infoDoc->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);
        }
    }

    function barcode($slug=NULL)
    {
        $this->load->library('document_library');

        if(isset($slug) && $slug)
        {
            $this->document_library->generareBarcode($slug);
        }
    }
}