<?php 
 /**
  * 
  */
 class Retour_Vente extends CI_Controller
 {

  function __construct()
  {
    parent::__construct();
    $this->load->library('Mylibrary');
    $this->ci = & get_instance();
    $this->ci->load->library("user_agent");
    // $this->Is_Connected();
    // $this->verification();

  }

  public function Is_Connected()
  {

   if (empty($this->session->userdata('SOCAR_ID_USER')))
   {
     redirect(base_url('Login/'));
   }
 }




 public function add_tocart()
 {

  $datas=array(
    'NUMERO_VENTE'=>$this->input->post('NUMERO_VENTE'),
    'PRIX_UNITAIRE'=>$this->input->post('PRIX_UNITAIRE'),
    'QUANTITE_COMMANDE'=>$this->input->post('QUANTITE_COMMANDE'),
    'ID_TAILLE_BOUTEILLE'=>$this->input->post('ID_TAILLE_BOUTEILLE'),
    'ID_VENTE'=>0,

  );

  $this->Model->insert_last_id('vente_details',$datas);

  $commune= $this->Model->getRequete("SELECT `ID_VENTE_DETAILS`,syst_taille_bouteille.DESCRIPTION,`QUANTITE_COMMANDE`,`PRIX_UNITAIRE`,prod_lot.LOT_PRODUCTION FROM `vente_details` JOIN syst_taille_bouteille ON syst_taille_bouteille.ID_TAILLE_BOUTEILLE = vente_details.ID_TAILLE_BOUTEILLE JOIN prod_lot ON prod_lot.ID_LOT =vente_details.ID_LOT WHERE `NUMERO_VENTE`  LIKE '".$this->input->post('NUMERO_VENTE')."'  ");

  $datas= '<table class="table">';
  $datas.='<tr>
  <td><b>Taille</b></td>
  <td><b>Lot</b></td>
  <td class="text-right"><b>Prix Unitaire</b></td>
  <td class="text-right"><b>Quantite</b></td>
  <td class="text-right"><b>Total</b></td>
  <td></td>
  </tr>';
  $totolpayabe =0;
  foreach($commune as $commun){
    $ptotal = $commun["QUANTITE_COMMANDE"]*$commun["PRIX_UNITAIRE"];
    $totolpayabe +=$ptotal;    
    $datas.= '<tr>
    <td>'.$commun["DESCRIPTION"].'</td>
    <td>'.$commun["LOT_PRODUCTION"].'</td>
    <td class="text-right">'.$commun["PRIX_UNITAIRE"].'</td>
    <td class="text-right">'.$commun["QUANTITE_COMMANDE"].'</td>
    <td class="text-right">'.$ptotal.'</td>
    <td><a class="btn btn-danger btn-xs" onclick="remove_cart('.$commun['ID_VENTE_DETAILS'].')" href="#" role="button">Enlever</a>
    </td>
    </tr>';

  }
  $datas.='<tr>
  <td colspan="3"><b>Total</b></td>

  <td class="text-right"><b>'.$totolpayabe.'</b></td>
  <td></td>
  </tr>';
  $datas.= '</table>';
  echo $datas;
}

  // function get_commune($prov){
  //   $comm = $this->Model->getList('syst_communes',array('PROVINCE_ID'=>$prov));
  //   $html = '<option value="" > --- </option>';
  //   foreach ($comm as $comm) {
  //     $html .= '<option value="'.$comm['COMMUNE_ID'].'">'.$comm['COMMUNE_NAME'].'</option>';
  //   }
  //   echo $html;

  // }


public function add()
{

  $NUMERO_VENTE=$this->input->post('NUMERO_VENTE');
  $ID_CLIENT=$this->input->post('ID_CLIENT');
  $ID_VENTE_STATUT=1;
  $DATE_COMMANDE=$this->input->post('DATE_COMMANDE');


  $dataclient = array(          
    'NUMERO_VENTE'=>$NUMERO_VENTE,  
    'ID_CLIENT'=>$ID_CLIENT,  
    'ID_VENTE_STATUT'=>$ID_VENTE_STATUT,  
    'DATE_COMMANDE'=>$DATE_COMMANDE,
  );
  $this->form_validation->set_rules('ID_CLIENT', 'Client', 'required');
  $this->form_validation->set_rules('DATE_COMMANDE', 'Date', 'required');


    //SI Valide
  if ($this->form_validation->run() == FALSE){        

    $title = "Enregistrement Commande";

    $data['typeclient']=$this->Model->getList('client_client',array());
    $data['tailbout']=$this->Model->getList('syst_taille_bouteille',array());
    $data['title'] = $title;

    $crequette= $this->Model->getRequeteOne("SELECT COUNT(ID_VENTE) AS NOMBRE FROM `vente_vente`");
    $number1 = $crequette['NOMBRE'] + 1;
    $formatted1 = str_pad($number1, 4, '0', STR_PAD_LEFT);
    $data['NUMERO_VENTE'] = 'V-'.$formatted1;
    

    $message = "<div class='alert alert-danger' id='message'>
    Donne manquantes, Processus échoué.
    <button type='button' class='close' data-dismiss='alert'>&times;</button>
    </div>";


    $this->session->set_flashdata(array('message'=>$message));
    $this->load->view("Commande_Add_View",$data);

  }else{
        // prod_production

    $ID_VENTE = $this->Model->insert_last_id('vente_vente',$dataclient);
    $this->Model->update('vente_details',array('NUMERO_VENTE'=>$NUMERO_VENTE),array('ID_VENTE'=>$ID_VENTE));
    $gettot= $this->Model->getRequeteOne("SELECT SUM((QUANTITE_COMMANDE*PRIX_UNITAIRE)) AS TOTAL FROM `vente_details` WHERE `ID_VENTE` = ".$ID_VENTE."");
    $this->Model->update('vente_vente',array('ID_VENTE'=>$ID_VENTE),array('MONTANT_TOTAL'=>$gettot['TOTAL']));

    $message = "<div class='alert alert-success'  id='message'>
    Enregistrement fait avec succès.
    <button type='button' class='close' data-dismiss='alert'>&times;</button>
    </div>";       
    $this->session->set_flashdata(array('message'=>$message));
    redirect(base_url('vente/Commande'));
  }
}





public function index()
{

  $data['title'] = "Retour Vente";
  $this->load->view('Retour_Vente_Add_View',$data);

}

public function listing()
{

  $data['title'] = "Retour Vente";
  $this->load->view('Retour_Vente_List_View',$data);

}

public function retourv()
{
  $idVenteDetails = $this->input->post('ID_VENTE_DETAILS');
  $quantiteRetourne = $this->input->post('QUANTITE_RETOURNE');

  $vent = $this->Model->getOne('vente_details', array('ID_VENTE_DETAILS' => $idVenteDetails));

  if($quantiteRetourne <= $vent['QUANTITE_LIVRE'] ){

    $quantiteRestant=$vent['QUANTITE_LIVRE'] - $quantiteRetourne;
    $prixRestant=$quantiteRestant*$vent['PRIX_UNITAIRE'];

    $updateResult = $this->Model->update('vente_details', 
      array('ID_VENTE_DETAILS' => $idVenteDetails), 
      array('QUANTITE_RETOURNE' => $quantiteRetourne,'QUANTITE_LIVRE' => $quantiteRestant)
    );
    

    $this->Model->update('vente_vente', 
      array('ID_VENTE' => $vent['ID_VENTE']), 
      array('MONTANT_TOTAL' =>$prixRestant ,'DATE_RETOUR' => date('Y-m-d'))
    );

    echo '1';
  } else {
        echo '2'; // Error
      }
    }

    // public function verification()
    // {
    //     $todaydate = date('Y-m-d'); 
    //     $liste = $this->Model->getRequete('SELECT ID_ASSURANCE FROM `voiture_assurance` WHERE 1 AND DATE_FIN < "'.$todaydate.'" AND ID_STATUS = 1');
    //     foreach ($liste as $key) {
    //       $this->Model->update('voiture_assurance',array('ID_ASSURANCE'=>$key['ID_ASSURANCE']),array('ID_STATUS'=>5));
    //     }
    // }


  //   public function modifier()
  // {
  //     $title = "Modification Garage";
  //     $GARAGE_ID =$this->uri->segment(4);
  //     $onedetail = $this->Model->getOne('voiture_garage',array('GARAGE_ID'=>$GARAGE_ID));
  //     $approvisionnement = array(
  //              'GARAGE_ID'=>$onedetail['GARAGE_ID'],
  //              'GARAGE_NOM'=>$onedetail['GARAGE_NOM'],       
  //              'PROVINCE_ID'=>$onedetail['PROVINCE_ID'],       
  //              'COMMUNE_ID'=>$onedetail['COMMUNE_ID'],       
  //              'province'=>$this->Model->getList('syst_provinces',array()),
  //              'commune'=>$this->Model->getList('syst_communes',array()),
  //             ); 
    

  //       $data['title'] = $title;
  //       $data['approv'] = $approvisionnement;


  //   $this->load->view("Garage_Update_View",$data);
  // }

  // public function update_garage()
  // {

  //    $data = array(          
  //       'GARAGE_NOM'=>$this->input->post('GARAGE_NOM'),  
  //       'PROVINCE_ID'=>$this->input->post('PROVINCE_ID'),  
  //       'COMMUNE_ID'=>$this->input->post('COMMUNE_ID'), 
  //       );

  //    $this->form_validation->set_rules('GARAGE_NOM', 'Nom du garage', 'required');
  //    $this->form_validation->set_rules('PROVINCE_ID', 'Province', 'required');
  //    $this->form_validation->set_rules('COMMUNE_ID', 'Commune', 'required');
  //    $title = "Modification Garage";
  //    $GARAGE_ID =$this->input->post('GARAGE_ID');

  //   //SI Valide
  //    if ($this->form_validation->run() == FALSE){        


  //     // echo $GARAGE_ID;
  //     // 
  //     $onedetail = $this->Model->getOne('voiture_garage',array('GARAGE_ID'=>$GARAGE_ID));
  //     // print_r($onedetail);
  //     // exit();
  //     $approvisionnement = array(
  //              'GARAGE_ID'=>$onedetail['GARAGE_ID'],
  //              'GARAGE_NOM'=>$onedetail['GARAGE_NOM'],       
  //              'PROVINCE_ID'=>$onedetail['PROVINCE_ID'],       
  //              'COMMUNE_ID'=>$onedetail['COMMUNE_ID'],       
  //              'province'=>$this->Model->getList('syst_provinces',array()),
  //              'commune'=>$this->Model->getList('syst_communes',array()),
  //             ); 
    

  //       $data['title'] = $title;
  //       $data['approv'] = $approvisionnement;


  //   // $this->load->view("Garage_Update_View",$data);

  //       $message = "<div class='alert alert-danger' id='message'>
  //                           Donne manquantes, Processus échoué.
  //                           <button type='button' class='close' data-dismiss='alert'>&times;</button>
  //                     </div>";


  //       $this->session->set_flashdata(array('message'=>$message));
  //      $this->load->view("Garage_Update_View",$data);

  //     }else{

  //       $this->Model->update('voiture_garage',array('GARAGE_ID'=>$GARAGE_ID),$data);

  //         $message = "<div class='alert alert-success'  id='message'>
  //                           Enregistrement fait avec succès.
  //                           <button type='button' class='close' data-dismiss='alert'>&times;</button>
  //                     </div>";       
  //       $this->session->set_flashdata(array('message'=>$message));
  //       redirect(base_url('voiture/Garage/listing'));
  //     }
  // }

  }                        