<?php

/**
 * Created by PhpStorm.
 * User: Utilisateur
 * Date: 2019-04-23
 * Time: 10:21
 */
class Paiements_model extends CI_Model
{

    public function __construct()
    {
        $this->load->database();
        $this->load->helper('date');
        $this->load->model('Projets_model');

    }
    public function mod_getRecords_paiements($facture)
    {

        // list la bb client
        $this->db->select('*');
        $this->db->from('pai_paiements');
        $this->db->join('pai_genres', 'pai_genres.gen_id=pai_paiements.pai_gen_id', 'left');
        $this->db->join('usa_usagers', 'pai_paiements.pai_user =  usa_usagers.usa_id ', 'left');


        //$this->db->where('det_con_active', 1);


        $this->db->where('pai_no_facture', $facture );

        $this->db->order_by("pai_date");

        $query = $this->db->get();

        return $query->result_array();
    }
    public function mod_listpaiement($facture=0,$excel) {



        // $recordCount = $this->Clients_model->getRecordCount();
        //$client_list=$this->Config_model->conf_getprojetsclients($record);
        $client_list=$this->mod_getRecords_paiements($facture);

        // creation du tableau

        // prepare header

        //$mem_link_new=anchor('clients/form/0' , ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-plus-sign" ');

       // $mem_link_new='<button id="submit_btn" type="submit" class="btn btn-primary btn-circle glyphicon glyphicon-plus"></button> ';
        $mem_link_new='';
        //$mem_link_projet=anchor('projets/createRecord/0/'.$record, ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-briefcase" ');
        $mem_link_projet='';
        $header=array(
            '',
            'Date',
            'Créer par',
            'Type',
            'note','Montant'  );
        // prépare les donnés du tableau
        $nbitem=0;
        $mem_excel['excel']=array();
        foreach($client_list as $row)
        {   $nbitem++;
            // faire le link pour edit
             $mem_link_edit=  '<a  id="pk_1" data-facture="" data-id="'.$row['pai_id'].'" class="btn btn-primary btn-circle glyphicon glyphicon-pencil"> </a>';


            // <a href="javascript:void(0);" class="btn btn-primary btn-circle"><i ></i></a> ';
            $data_row = array();

            $data_row[] = array('data'=> $mem_link_edit, 'align' => 'left', 'width' => '2');
            $data_row[] = array('data'=>$row['pai_date'], 'align' => 'left', 'width' => '13%');
            $data_row[] = array('data'=>$row['usa_prenom'].''.$row['usa_nom'], 'align' => 'left');

            $data_row[] = array('data'=>$row['gen_nom_fr'], 'align' => 'left');

            $data_row[] = array('data'=>$row['pai_note'], 'align' => 'left');
            $data_row[] = array('data'=>$row['pai_montant'], 'align' => 'left','format'=>'argent');


            $tabular_data[] = $data_row;

            if($excel==2){
                $data_row_excel = array();


                $data_row_excel[] = array('data'=>'');
                $data_row_excel[] = array('data'=>'');
                $data_row_excel[] = array('data'=>'');
                $data_row_excel[] = array('data'=>'');
                $data_row_excel[] = array('data'=>'');
                $data_row_excel[] = array('data'=>'');

                $data_row_excel[] = array('data'=>$row['pai_date'], 'align' => 'left', 'width' => '13%','color'=>'b3b3ff');
               // $data_row[] = array('data'=>$row['usa_prenom'].''.$row['usa_nom'], 'align' => 'left');

                $data_row_excel[] = array('data'=>$row['gen_nom_fr'], 'align' => 'left','color'=>'b3b3ff');

                $data_row_excel[] = array('data'=>$row['pai_note'], 'align' => 'left','color'=>'b3b3ff');
                $data_row_excel[] = array('data'=>number_format($row['pai_montant'],2,'.',''), 'align' => 'left','format'=>'argent','color'=>'b3b3ff');

                $mem_excel['excel'][]=$data_row_excel;

            }

        }
        $data_row_excel = array();
        $data_row_excel[] = array('data'=>'');
        $mem_excel['excel'][]=$data_row_excel;
        $template = array(
            'table_open'            => '<table border="0" cellpadding="4" cellspacing="0" class="table table-striped table-bordered table-hover">',

            'thead_open'            => '<thead  >',
            'thead_close'           => '</thead>',

            'heading_row_start'     => '<tr>',
            'heading_row_end'       => '</tr>',
            'heading_cell_start'    => '<th style="background-color: #003333">',
            'heading_cell_end'      => '</th>',

            'tbody_open'            => '<tbody>',
            'tbody_close'           => '</tbody>',

            'row_start'             => '<tr>',
            'row_end'               => '</tr>',
            'cell_start'            => '<td>',
            'cell_end'              => '</td>',

            'row_alt_start'         => '<tr>',
            'row_alt_end'           => '</tr>',
            'cell_alt_start'        => '<td>',
            'cell_alt_end'          => '</td>',

            'table_close'           => '</table>'
        );

        $this->table->set_template($template);

        $this->table->set_heading($header);

        if(!isset($tabular_data))
            $tabular_data=array();
        $tableau_sortie= $this->table->generate($tabular_data);

        if($nbitem==0)
            $tableau_sortie='vide';


        $mem_sortie['tableau_sortie']=$tableau_sortie;
        $mem_sortie['excel']=$mem_excel['excel'];
        return $mem_sortie;


    }

    public function mod_loadData_list($record=0,$filtre1='',$filtre2='',$filtre3='',$date_debut="2019-01-01",$date_fin="2025-01-01", $listactif = 1, $model='',$excel) {

        $filtre1=($filtre1=='null'?'':$filtre1);
        $filtre2=($filtre2=='null'?'':$filtre2);
        $filtre3=($filtre3=='null'?'':$filtre3);

            $recordPerPage = 9999;

        $config["cur_page"] = $record;
        if($record != 0){
            $record = ($record-1) * $recordPerPage;
        }

         $recordCount2 = $this->Paiements_model->mod_getRecordCount();

         $recordCount = $this->Paiements_model->mod_getRecordCountfilter($filtre1,$filtre2,$filtre3);



         $client_list = $this->Paiements_model->mod_getRecords($record,$recordPerPage,$filtre1,$filtre2,$filtre3,$date_debut,$date_fin);


        //echo '<pre>', print_r($client_list, true), '</pre>';

        $config['base_url'] = base_url().'index.php/Fournisseurs/loadData_list';
        $config['use_page_numbers'] = TRUE;
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['total_rows'] = $recordCount;
        $config['per_page'] = $recordPerPage;

        $choice = $config["total_rows"] / $config["per_page"];
        $config["uri_segment"] = 2;
        $config["num_links"] = 2;
        $config['full_tag_open'] = '<div ><ul class="pagination">';
        $config['full_tag_close'] = '</ul></div><!--pagination-->';

        $config['first_link'] = '&laquo; First';
        $config['first_tag_open'] = '<li class="prev page">';
        $config['first_tag_close'] = '</li>';

        $config['last_link'] = 'Last &raquo;';
        $config['last_tag_open'] = '<li class="next page">';
        $config['last_tag_close'] = '</li>';

        $config['next_link'] = 'Next &rarr;';
        $config['next_tag_open'] = '<li class="next page">';
        $config['next_tag_close'] = '</li>';

        $config['prev_link'] = '&larr; Previous';
        $config['prev_tag_open'] = '<li class="prev page">';
        $config['prev_tag_close'] = '</li>';

        $config['cur_tag_open'] = '<li class="active"><a href="">';
        $config['cur_tag_close'] = '</a></li>';

        $config['num_tag_open'] = '<li class="page">';
        $config['num_tag_close'] = '</li>';
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['recordCount']=$recordCount2;
        // creation du tableau


        // prepare header

      //  if ($model == 'projets'){   $mem_link_new='';
      //         }else{
            $mem_link_new=anchor('fournisseurs/form/0' , ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-pencil" ');

     //   }
        $data['model']=$model;
        $mem_excel='<a id="excel" data-id="1" class="btn btn-primary btn-circle fa fa-cloud-download"> </a><a id="excel" data-id="2" class="btn btn-success btn-circle fa fa-cloud-download"> </a>';
        $header=array( $mem_excel,
            'No facture',
            'Compagnie',
            'No projet',
            'Nom projet',
            'Date facture',
            '$$$','','30','60','90','+' );

        if ($excel!=0){
            $mem_excel_output['header']=array('Client','Date de facturation',
                'No. de facture',
                'No. de projet',
                'Total avant tx',
                'TPS',
                'TVQ',
                'TVH',
                'OPC',
                'Total',
                'Dépôt/paiement',
                'À recevoir','Nb jours','OPC avant');
            $mem_excel_output['headerwidth']=array(45,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15);
        }
        $nbitem=0;


        // filter
        global $mem_data;
        $data_row = array();
        $data_row[]=array('data'=>'Filtre', 'align' => 'left');
        // -------------------------------------------------------------------------
        //      $mem_champ='filtre_fournisseurs_1';
        //       $mem_value=trim($filtre1);
        //       $this->FxForm_model->fxinputtxt($mem_champ,$mem_value,'','','','filtre_fournisseurs_1');

        //    $mem_filtre=form_input($mem_data['input'][$mem_champ]);
        //      $data_row[]=array('data'=>$mem_filtre, 'align' => 'left');
        // -------------------------------------------------------------------------
        $mem_champ='filtre_fournisseurs_1';
        $mem_value=trim($filtre1);
        $this->FxForm_model->fxinputtxt($mem_champ,$mem_value,'','','','filtre_fournisseurs_1',7);
        $mem_filtre=form_input($mem_data['input'][$mem_champ]);
        $data_row[]=array('data'=>$mem_filtre, 'align' => 'left');

        // -------------------------------------------------------------------------
        $mem_champ='filtre_fournisseurs_2';
        $mem_value=trim($filtre2);
        $this->FxForm_model->fxinputtxt($mem_champ,$mem_value,'','','','filtre_fournisseurs_2');
        $mem_filtre=form_input($mem_data['input'][$mem_champ]);
        $data_row[]=array('data'=>$mem_filtre, 'align' => 'left');

        // -------------------------------------------------------------------------

        // echo form_dropdown($mem_champ,$select[$mem_champ]['choix'],$select[$mem_champ]['value']);
        // -------------------------------------------------------------------------
        $mem_champ='filtre_fournisseurs_3';
        $mem_value=trim($filtre3);
        $this->FxForm_model->fxinputtxt($mem_champ,$mem_value,'','','','filtre_fournisseurs_3',4);
        $mem_filtre=form_input($mem_data['input'][$mem_champ]);
        $data_row[]=array('data'=>$mem_filtre, 'align' => 'left');
        // -------------------------------------------------------------------------
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
        $data_row[]=array('data'=>'', 'align' => 'left');
// prépare les donnés du tableau







        $tabular_data[] = $data_row;



$idmem=0;
        if ($client_list!=null){
        foreach($client_list as $row)
        {   $nbitem++;
            // faire le link pour edit
            $mem_link_edit="";
            $idmem=$idmem+1;
                // $mem_link_edit=anchor('fournisseurs/form/'.$row['com_id'], ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-plus-sign" ');
            $mem_link_edit = '<a  id="pk_1" data-id="0" data-facture="'.$row['det_fac_numero'].'" class="btn btn-primary btn-circle glyphicon glyphicon-pencil"> </a>';

            $mem_link_projet = anchor('projets/form/' . $row['proj_id'], ' ', array('class'=> 'btn btn-primary btn-circle glyphicon glyphicon-edit', 'target' => 'projet' ));


            // <a href="javascript:void(0);" class="btn btn-primary btn-circle"><i ></i></a> ';
            $data_row = array();
            $data_row[] = array('data'=> $mem_link_edit.$mem_link_projet, 'align' => 'left');
            //    $data_row[] = array('data'=>$row['com_num_client'], 'align' => 'left');
            $data_row[] = array('data'=>$row['det_fac_numero'], 'align' => 'left');
            $data_row[] = array('data'=>$row['com_compagnie'], 'align' => 'left','width'=>15);
            $data_row[] = array('data'=>$row['proj_numero'], 'align' => 'left','width'=>3);
            //  $data_row[] = array('data'=>$row['rep_prenom']." ".$row['rep_nom'], 'align' => 'left');
            $data_row[] = array('data'=>$row['proj_nom'], 'align' => 'left','width'=>200);
            $data_row[] = array('data'=>date("Y-m-d",strtotime($row['det_fac_envoi'])), 'align' => 'left');
            $data_row[] = array('data'=>number_format($row['det_fac_montant'],2,'.',' '), 'align' => 'left');

            $mem_facture=' <a target="_blank" href="'. base_url().'/pdf/pdf2019/facturation/'. $row['det_fac_pdf'] .'" class="btn btn-primary btn-circle glyphicon glyphicon-list-alt"></a>';


            $data_row[] = array('data'=>$mem_facture, 'align' => 'left');

            $bal=$row['det_fac_montant']-$row['tot_montant'];

            if ($row['days']<=30 && $bal<>0){
                $data_row[] = array('data'=>number_format($bal,2,'.',' '), 'align' => 'left','class' => 'j30');
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>'', 'align' => 'left');
            }
            if ($row['days']>30 && $row['days']<=60 && $bal<>0){
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>number_format($bal,2,'.',' '), 'align' => 'left','class' => 'j60');
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>'', 'align' => 'left');
            }
            if ($row['days']>60 && $row['days']<=90 && $bal<>0){
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>number_format($bal,2,'.',' '), 'align' => 'left','class' => 'j90');

                $data_row[] = array('data'=>'', 'align' => 'left');
            }
            if ($row['days']>90 && $bal<>0){
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>'', 'align' => 'left');
                $data_row[] = array('data'=>number_format($bal,2,'.',' '), 'align' => 'left','class' => 'jplus');

                $data_row[] = array('data'=>'', 'align' => 'left');
            }
           // $data_row[] = array('data'=>$row['days'], 'align' => 'left');
            $tabular_data[] = $data_row;
             //print_r( $row);

             $mem_projets=$this->mod_listpaiement($row['det_fac_numero'],$excel);

            if ($excel!=0){
                $data_row_excel = array();
                $data_row_excel[] = array('data'=>$row['com_compagnie'], 'align' => 'left');
                $data_row_excel[] = array('data'=>date("Y-m-d",strtotime($row['det_fac_envoi'])), 'align' => 'left');
                $data_row_excel[] = array('data'=>$row['det_fac_numero'], 'align' => 'left');
                $data_row_excel[] = array('data'=>$row['proj_numero'], 'align' => 'left','width'=>3);
                $data_row_excel[] = array('data'=>number_format($row['det_fac_avanttx'],2,'.',''), 'align' => 'left','format'=>'argent');


                $data_row_excel[] = array('data'=>number_format($row['det_fac_tps'],2,'.',''), 'align' => 'left','format'=>'argent');
                $data_row_excel[] = array('data'=>number_format($row['det_fac_tvq'],2,'.',''), 'align' => 'left','format'=>'argent');
                 $data_row_excel[] = array('data'=>number_format($row['det_fac_tvh'],2,'.',''), 'align' => 'left','format'=>'argent');
                $data_row_excel[] = array('data'=>number_format($row['det_fac_opc'],2,'.',''), 'align' => 'left','format'=>'argent');
                $data_row_excel[] = array('data'=>number_format($row['det_fac_montant'],2,'.',''), 'align' => 'left','format'=>'argent');
                $data_row_excel[] = array('data'=>number_format($row['det_fac_depot'],2,'.',''), 'align' => 'left','format'=>'argent');


                $data_row_excel[] = array('data'=>number_format($bal,2,'.',''), 'align' => 'left','format'=>'argent');
                if($bal<>0)
                   $data_row_excel[] = array('data'=>$row['days'], 'align' => 'left','width'=>3);
                $data_row_excel[] = array('data'=>number_format($row['det_fac_opc_avant'],2,'.',''), 'align' => 'left','format'=>'argent');

                $mem_excel_output['data'][]=$data_row_excel;

                $mem_excel_output['data']=array_merge($mem_excel_output['data'],$mem_projets['excel']);
            }





             if($mem_projets['tableau_sortie']==='vide'){
                $mem_projets="";
                $expend="";
            }
            else
            {
                $mem_projets='<div style="display:none" id="hide_'.$row['proj_id'].'_'. $idmem.'">'.$mem_projets['tableau_sortie'].'</div>';

                $expend='<a id="bt_hide_'.$row['proj_id'].'_'. $idmem.'" data-id="hide_'.$row['proj_id'].'_'. $idmem.'"  class="fa fa-fw fa-dot-circle-o"> </a>';

            }

           $data_row = array();
            $data_row[] = array('data'=>$expend );
            $data_row[] = array('data'=>$mem_projets,'colspan' => 6 );

            $tabular_data[] = $data_row;

        }

    }
        $template = array(
            'table_open'            => '<table border="0" cellpadding="4" cellspacing="0" class="table table-striped table-bordered table-hover">',

            'thead_open'            => '<thead>',
            'thead_close'           => '</thead>',

            'heading_row_start'     => '<tr>',
            'heading_row_end'       => '</tr>',
            'heading_cell_start'    => '<th>',
            'heading_cell_end'      => '</th>',

            'tbody_open'            => '<tbody>',
            'tbody_close'           => '</tbody>',

            'row_start'             => '<tr>',
            'row_end'               => '</tr>',
            'cell_start'            => '<td>',
            'cell_end'              => '</td>',

            'row_alt_start'         => '<tr>',
            'row_alt_end'           => '</tr>',
            'cell_alt_start'        => '<td>',
            'cell_alt_end'          => '</td>',

            'table_close'           => '</table>'
        );

        $this->table->set_template($template);
        $this->table->set_heading($header);
        $this->table->set_heading($header);
        $tableau_sortie= $this->table->generate($tabular_data);

        if ($excel!=0){
            //$mem_excel_output['data']=$tabular_data;

            $data['fichier']="paiement.xls";
            $mem_excel_output['fichier']="paiement";
          //  $mem_excel_output['titre']="depart du ".$debut.' @ '.$fin;
            $mem_excel_output['titre']="rapport en date du ".date("Y-m-d H:i");;
            $mem_parameter=array('premiere_ligne'=>0);

            $this->Config_model->excel($mem_excel_output,$mem_parameter);
        }

        $data['list'] = $tableau_sortie;

        return $data ;
    }

    public function mod_getRecords($rowno, $rowperpage, $filtre1 = "", $filtre2 = "", $filtre3 = "",$date_debut="2019-01-01",$date_fin="2025-01-01", $langue = 'fr')
    {

        //    $this->db->select('*,DATEDIFF( now(),det_fac_envoi) AS days,proj_entete.proj_client_id as cli_id,cli_contacts.con_prenom as cli_contact_prenom,cli_contacts.con_nom as cli_contact_nom,fou_contacts.con_courriel as fou_contact_courriel,fou_contacts.con_prenom as fou_contact_prenom,fou_contacts.con_nom as fou_contact_nom,cli_compte.com_compagnie as com_compagnie_client,fou_compte.com_compagnie as com_compagnie_fou,sum(pai_paiements.pai_montant) as tot_montant');
        $this->db->select('*,DATEDIFF( now(),det_fac_envoi) AS days,proj_entete.proj_client_id as cli_id,cli_contacts.con_prenom as cli_contact_prenom,cli_contacts.con_nom as cli_contact_nom,fou_contacts.con_courriel as fou_contact_courriel,fou_contacts.con_prenom as fou_contact_prenom,fou_contacts.con_nom as fou_contact_nom,cli_compte.com_compagnie as com_compagnie_client,fou_compte.com_compagnie as com_compagnie_fou');
        $this->db->from('proj_details_details');
      //   $this->db->join('pai_paiements','pai_paiements.pai_no_facture=proj_details_details.det_fac_numero', 'left');
        $this->db->join('proj_details', 'proj_details.proj_det_id=proj_details_details.proj_det_id', 'left');
        $this->db->join('proj_entete', 'proj_entete.proj_id=proj_details.proj_ent_id', 'left');
        $this->db->join('fou_compte', 'fou_compte.com_id=proj_details.proj_fou_id', 'left');
        $this->db->join('pro_descriptions', 'pro_descriptions.des_id=proj_details.proj_prod_id', 'left');
        $this->db->join('fou_genres', 'fou_genres.gen_id=pro_descriptions.des_ref_type', 'left');
        $this->db->join('cli_compte', 'cli_compte.com_id=proj_entete.proj_client_id', 'left');
        $this->db->join('fou_contacts', 'fou_contacts.con_id=proj_details_details.det_res_contact_id', 'left');
        $this->db->join('cli_contacts', 'cli_contacts.con_id=proj_entete.proj_contact_principale', 'left');
        $this->db->group_by('det_fac_lot_numero');
        $this->db->where('det_fac_lock', 1);
        $this->db->where("det_fac_envoi between '".$date_debut." 00:00:00' and '".$date_fin." 23:59:00'");
        $this->db->order_by("proj_details_details.det_fac_numero");
        $this->db->order_by("proj_details_details.det_fac_montant desc");

        if ($filtre1 != "")
            $this->db->where("det_fac_numero LIKE '%$filtre1%'");
        if ($filtre2 != "")
            $this->db->where("cli_compte.com_compagnie LIKE '%$filtre2%'");
        if ($filtre3 != "")
            $this->db->where("proj_numero LIKE '%$filtre3%'");

        $this->db->limit($rowperpage, $rowno);

        $query = $this->db->get();
       echo $this->db->last_query();
        $four = $query->result_array();
        // ajouter la liste des type
        $sortie = array();
        foreach ($four as $row){
            $this->db->select('sum(pai_paiements.pai_montant) as tot_montant');
            $this->db->from('pai_paiements');
            $this->db->where("pai_no_facture='".$row['det_fac_numero']."'");
            $query = $this->db->get();
            $montant = $query->result_array();
            $row['tot_montant']=$montant[0]['tot_montant'];
            $sortie[]=$row;
        }


        return  $sortie;
    }

    public function mod_getRecords_contacts($id, $langue = 'fr')
    {
        // list la bb client
        $this->db->select('*,fou_contacts_roles.rol_nom as role');
        $this->db->from('fou_contacts');
        $this->db->join('fou_contacts_roles', 'fou_contacts_roles.rol_id=fou_contacts.con_role_id', 'left');
        $this->db->where('fou_contacts.ref_id', $id);
        $this->db->where('fou_contacts.con_actif', 1);
        $query = $this->db->get();
        return $query->result_array();
    }

    public function mod_getRecord($id, $langue = 'fr')
    {
        // trouve un enregiestrement
        $this->db->select('*');
        $this->db->from('pai_paiements');
        $this->db->join('pai_genres', 'pai_genres.gen_id=pai_paiements.pai_gen_id', 'left');
        $this->db->join('usa_usagers', 'pai_paiements.pai_user =  usa_usagers.usa_id ', 'left');


        $this->db->where('pai_id=' . $id);

        $this->db->limit(1);

        $query = $this->db->get();
        return $query->row();
    }

    public function mod_saveRecordbd($id, $data, $pref)
    {


        // creation de la chaine de save
        $mem_data = array();
        // ajoute les checkbox
        if (!isset($data['com_actif']))
            $data['com_actif'] = 0;
        foreach ($data as $key => $value) {


            if (substr($key, 0, strlen($pref)) == $pref) {
                switch ($key) {
                    case 'com_ref_type':
                        $mem_value = '';
                        foreach ($data['com_ref_type'] as $key2 => $value2) {
                            $mem_value = $mem_value . $value2 . ',';

                        }
                        $mem_value = rtrim($mem_value, ",");
                        $mem_data['com_ref_type'] = $mem_value;
                        break;

                    default:
                        $mem_data[$key] = $value;
                }

            }

        }
        $mem_data['com_modif'] = date("Y-m-d H:i:s");
        $mem_where = "com_id =" . $id;

        $str = $this->db->update('fou_compte', $mem_data, $mem_where);
        $ok = true;

        return $ok;
    }



    public function mod_createRecordbdcontact($data, $pref, $ref_id)
    {


        $mem_data = array();
        foreach ($data as $key => $value) {
            if (substr($key, 0, strlen($pref)) == $pref) {
                $mem_data[$key] = $value;
            }

        }
        $mem_data['ref_id'] = $ref_id;
        $mem_data['con_creation'] = date("Y-m-d H:i:s");
        $mem_data['con_actif'] = 1;

        $str = $this->db->insert('fou_contacts', $mem_data);

        $ok = true;

        return;
    }

    public function mod_deleteRecordbdcontact($id)
    {

        $mem_data['con_actif'] = 0;
        $mem_where = "con_id =" . $id;

        $str = $this->db->update('fou_contacts', $mem_data, $mem_where);


        $ok = true;

        return;
    }

    public function mod_getRecordCount()
    {
        $this->db->select('count(*) as allcount');
        $this->db->from('proj_details_details');
        $this->db->join('proj_details', 'proj_details.proj_det_id=proj_details_details.proj_det_id', 'left');
        $this->db->join('proj_entete', 'proj_entete.proj_id=proj_details.proj_ent_id', 'left');
        $this->db->join('fou_compte', 'fou_compte.com_id=proj_details.proj_fou_id', 'left');
        $this->db->join('pro_descriptions', 'pro_descriptions.des_id=proj_details.proj_prod_id', 'left');
        $this->db->join('fou_genres', 'fou_genres.gen_id=pro_descriptions.des_ref_type', 'left');
        $this->db->join('cli_compte', 'cli_compte.com_id=proj_entete.proj_client_id', 'left');
        $this->db->join('fou_contacts', 'fou_contacts.con_id=proj_details_details.det_res_contact_id', 'left');
        $this->db->join('cli_contacts', 'cli_contacts.con_id=proj_entete.proj_contact_principale', 'left');
        $this->db->group_by('det_fac_lot_numero');

        $this->db->where('det_fac_lock', 1);
        $query = $this->db->get();
        $result = $query->result_array();
        return $result[0]['allcount'];
    }

    public function mod_getRecordCountfilter($filtre1 = "", $filtre2 = "", $filtre3 = "")
    {
        $this->db->select('count(*) as allcount');
          $this->db->from('proj_details_details');

        $this->db->join('proj_details', 'proj_details.proj_det_id=proj_details_details.proj_det_id', 'left');
        $this->db->join('proj_entete', 'proj_entete.proj_id=proj_details.proj_ent_id', 'left');
        $this->db->join('fou_compte', 'fou_compte.com_id=proj_details.proj_fou_id', 'left');
        $this->db->join('pro_descriptions', 'pro_descriptions.des_id=proj_details.proj_prod_id', 'left');
        $this->db->join('fou_genres', 'fou_genres.gen_id=pro_descriptions.des_ref_type', 'left');
        $this->db->join('cli_compte', 'cli_compte.com_id=proj_entete.proj_client_id', 'left');
        $this->db->join('fou_contacts', 'fou_contacts.con_id=proj_details_details.det_res_contact_id', 'left');
        $this->db->join('cli_contacts', 'cli_contacts.con_id=proj_entete.proj_contact_principale', 'left');
        $this->db->group_by('det_fac_lot_numero');

        $this->db->where('det_fac_lock', 1);
        $query = $this->db->get();
        $result = $query->result_array();
        return $result[0]['allcount'];
    }

    public function mod_listcontact($record = 0)
    {


        // $recordCount = $this->Fournisseurs_model->getRecordCount();

        $client_list = $this->mod_getRecords_contacts($record);


        // creation du tableau


        // prepare header

        //$mem_link_new=anchor('clients/form/0' , ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-plus-sign" ');

        $mem_link_new = '<button id="submit_btn" type="submit" class="btn btn-primary btn-circle glyphicon glyphicon-plus"></button> ';


        $header=array('','Prénom',
            'Nom',
            '<i class="fa fa-fw fa-phone text-muted hidden-md hidden-sm hidden-xs"></i>Téléphone bureau',
            'Ext',
            '<i class="fa fa-fw fa-phone text-muted hidden-md hidden-sm hidden-xs"></i>Cellulaire',
            'Courriel',
            'Role');
        // prépare les donnés du tableau
        $nbitem = 0;
        foreach ($client_list as $row) {
            $nbitem++;
            // faire le link pour edit
            $mem_link_edit = anchor('fournisseurs/deletecontact/' . $row['con_id'] . '/' . $record, ' ', 'class="btn btn-primary btn-circle glyphicon glyphicon-trash" ');
            // <a href="javascript:void(0);" class="btn btn-primary btn-circle"><i ></i></a> ';
            $data_row = array();

            $data_row[] = array('data'=> $mem_link_edit, 'align' => 'left');
            $data_row[] = array('data'=>$row['con_prenom'], 'align' => 'left');
            $data_row[] = array('data'=>$row['con_nom'], 'align' => 'left');
            $data_row[] = array('data'=>$row['con_telephone'], 'align' => 'left');
            $data_row[] = array('data'=>$row['con_ext'],'width'=>'5', 'align' => 'left');
            $data_row[] = array('data'=>$row['con_telephone2'], 'align' => 'left');
            $data_row[] = array('data'=>$row['con_courriel'], 'align' => 'left');
            $data_row[] = array('data'=>$row['role'], 'align' => 'left');

            $tabular_data[] = $data_row;

        }
        $data_row = array();
        $data_row[] = array('data'=> $mem_link_new);
        $data_row[] = array('data'=> form_input(array('name'  => 'con_prenom','size'=>15)));
        $data_row[] = array('data'=> form_input(array('name'  => 'con_nom','size'=>15)));
        $data_row[] = array('data'=> form_input(array('name'  => 'con_telephone','size'=>15)));
        $data_row[] = array('data'=> form_input(array('name'  => 'con_ext','size'=>5)));
        $data_row[] = array('data'=> form_input(array('name'  => 'con_telephone2','size'=>15)));
        $data_row[] = array('data'=> form_input(array('name'  => 'con_courriel','size'=>15)));

        $mem_choix = $this->Config_model->conf_getRolesContactsFournisseur();
        $mem_roles = form_dropdown('con_role_id', $mem_choix);


        $data_row[] = array('data' => $mem_roles, 'align' => 'left');
        $tabular_data[] = $data_row;

        $template = array(
            'table_open' => '<table border="0" cellpadding="4" cellspacing="0" class="table table-striped table-bordered table-hover">',

            'thead_open' => '<thead  >',
            'thead_close' => '</thead>',

            'heading_row_start' => '<tr>',
            'heading_row_end' => '</tr>',
            'heading_cell_start' => '<th>',
            'heading_cell_end' => '</th>',

            'tbody_open' => '<tbody>',
            'tbody_close' => '</tbody>',

            'row_start' => '<tr>',
            'row_end' => '</tr>',
            'cell_start' => '<td>',
            'cell_end' => '</td>',

            'row_alt_start' => '<tr>',
            'row_alt_end' => '</tr>',
            'cell_alt_start' => '<td>',
            'cell_alt_end' => '</td>',

            'table_close' => '</table>'
        );

        $this->table->set_template($template);

        $this->table->set_heading($header);
        $tableau_sortie = $this->table->generate($tabular_data);


        return $tableau_sortie;


    }

    public function mod_getforminfo($id)
    {
        global $mem_data, $validation;

        $this->load->model('Config_model');
        $this->load->model('FxForm_model');
        // vas chercher les info de la fiche

        if ($id != 0)
            $info = $this->mod_getRecord($id);


        // prepare info pour chaque champs utilisé
        // input
        $mem_data['mem_id'] = $id;
        $mem_champ = 'pai_montant';
        $mem_value = ($id == 0 ? '' : $info->$mem_champ);
        $this->FxForm_model->fxinputtxt($mem_champ, $mem_value, 'Montant', '');
        $this->FxForm_model->fxvaliderequired($mem_champ);

 // -----------------------------------------------------------------------

        $mem_champ = 'pai_note';
        $mem_value = ($id == 0 ? '' : $info->$mem_champ);
        $this->FxForm_model->fxinputtxt($mem_champ, $mem_value, 'Note', '');
        // $this->FxForm_model->fxvaliderequired($mem_champ);
// -------------------------------------------------------------------------
        $mem_champ = 'pai_date';

        $mem_data['icon'][$mem_champ] = 'icon-append fa fa-calendar';
        $mem_value = ($id == 0 ? '' : $info->$mem_champ);

        $this->FxForm_model->fxinputtxt($mem_champ, $mem_value, 'Date', '', '', '');



        // -------------------------------------------------------------------------
        $mem_champ = 'pai_gen_id';

         $mem_value = ($id == 0 ? '' : $info->$mem_champ);
        $mem_data['select'][$mem_champ]['choix'] = $this->Config_model->conf_getGenresPaiement('fr');
        // value multipli select
        $mem_value = explode(',', $mem_value);

        $mem_data['select'][$mem_champ]['value'] = $mem_value;
        $mem_data['label'][$mem_champ] = 'Type';

        // -------------------------------------------------------------------------


        // -------------------------------------------------------------------------

        $mem_data['validation'] = $this->FxForm_model->fxValidation($validation['rule'], $validation['message']);


        return $mem_data;
    }
    public function mod_selectcontact($fournisseur_id,$langue='fr',$choix_vide=true)
    {


        $contacts=$this->Fournisseurs_model->mod_getRecords_contacts($fournisseur_id);
        // list la bb client


        $mem_sortie=array();
        if ($choix_vide)
            $mem_sortie[0]='';
        foreach  ($contacts as $pro ){
            $mem_sortie[$pro['con_id']]=$pro['con_prenom']." ".$pro['con_nom']." (".$pro['rol_nom'].")";

        }
        return $mem_sortie;


    }
    public function mod_createRecordbd($data, $pref, $id,$no_facture)
    {


        // creation de la chaine de save

        $mem_data = array();



        foreach ($data as $key => $value) {
            if (substr($key, 0, strlen($pref)) == $pref) {
                $mem_data[$key] = $value;
            }

        }



        if ($id == 0) {
            $mem_data['pai_user'] =$this->session->id ;
            $mem_data['pai_no_facture'] =$no_facture;

            $str = $this->db->insert('pai_paiements', $mem_data);
        } else {
            $mem_where = "pai_id =" . $id;

            $str = $this->db->update('pai_paiements', $mem_data, $mem_where);

        }
        $ok = true;

        return $this->db->insert_id();
    }
}