<?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` FROM `vente_details` JOIN syst_taille_bouteille ON syst_taille_bouteille.ID_TAILLE_BOUTEILLE = vente_details.ID_TAILLE_BOUTEILLE WHERE `NUMERO_VENTE`  LIKE '".$this->input->post('NUMERO_VENTE')."'  ");

  $datas= '<table class="table">';
  $datas.='<tr>
  <td><b>Taille</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 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'; 
  }
}

public function retour_vente()
{
    // Retrieve the selected IDs and quantities from the form
    $selectedIds = $this->input->post('SELECT'); // Get selected IDs
    $quantiteRetourne = $this->input->post('QUANTITE_LIVRE'); // Get quantities
    $prixRestant=0;
    // Check if any IDs were selected
    if (!empty($selectedIds) && is_array($selectedIds)) {
      foreach ($selectedIds as  $idVenteDetails) {
        $quantite = isset($quantiteRetourne[$idVenteDetails]) ? $quantiteRetourne[$idVenteDetails] : 0;

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

        if ($quantite > 0 && $quantite <= $vent['QUANTITE_LIVRE']) {
          $quantiteRestant = $vent['QUANTITE_LIVRE'] - $quantite;
          $prixRestant += $quantiteRestant * $vent['PRIX_UNITAIRE'];

          $this->Model->update(
            'vente_details',
            ['ID_VENTE_DETAILS' => $idVenteDetails],
            [
              'QUANTITE_RETOURNE' => $quantite,
              'QUANTITE_LIVRE' => $quantiteRestant
            ]
          );
        }
      }
        // Update the overall sale record
      $this->Model->update(
        'vente_vente',
        ['ID_VENTE' => $vent['ID_VENTE']],
        [
          'MONTANT_TOTAL' => $prixRestant,
          'DATE_RETOUR' => date('Y-m-d')
        ]
      );

        // Set success message
      $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(['message' => $message]);
    } else {
        // Set error message if no items were selected
      $message = "<div class='alert alert-danger' id='message'>
      Aucun élément sélectionné ou quantité invalide.
      <button type='button' class='close' data-dismiss='alert'>&times;</button>
      </div>";
      $this->session->set_flashdata(['message' => $message]);
    }

    // Redirect to the vente page
    redirect(base_url('vente/Retour_Vente'));
  }

}                        