<?php

function spai_bit_enviar_form($form, &$form_state){
  global $base_path;
  $form = array();
  $form['url'] = array(
    '#type' => 'item',
    '#markup' => 'URL: '.variable_get('spai_bit_url'),
  );

  $form['file'] = array(
    '#type' => 'file',
    '#title' => t('Fichero a enviar:'),
    '#description' => 'Sólo se permiten formatos "<strong>.csv</strong>"',
  );
  $form['submit'] = array(
		'#type'          => 'submit',
		'#value'         => 'Enviar Archivo',
	);
  //drupal_set_message(t('Ruta: @n',array('@n'=>getcwd())));
  return $form;
}

function spai_bit_enviar_form_validate($form, &$form_state){
  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('csv'),
  ));
  //drupal_set_message(t('filename: @n',array('@n'=>$file->filename)));
  if (!strpos(strtolower($file->filename),"_base") && 
     !strpos(strtolower($file->filename),"_via") &&
     !strpos(strtolower($file->filename),"_prog") &&
     !strpos(strtolower($file->filename),"_real"))
       form_set_error('file', t('No es un fichero Válido.'));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }   
}

function spai_bit_enviar_form_submit($form, &$form_state){
  $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  //drupal_set_message(t('fid: @n',array('@n'=>$file->fid)));
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);


  /*****************************/
  /*   ENVÍO DE FICHERO BASE   */
  /*****************************/
  if (strpos(strtolower($file->filename),"_base")) {
    $url = variable_get('spai_bit_url').'base';
    $fichero = getcwd().'/sites/default/files/'.str_replace('public://','',$file->uri);
    $registros = array();
    if (($gestor = fopen($fichero, "r")) !== FALSE) {
      while (($datos = fgetcsv($gestor, 1000, ";")) !== FALSE) {
        if (substr($datos[0],0,2) == "CE"){
          switch (substr($datos[0],2,2)){
            case "10":
              $conce = "VCM-503";
              break;
            case "02":
              $conce = "VAC-082";
              break;
            case "03":
              $conce = "VAC-226";
              break;
          }
        $anio = "20".$datos[1];
        $mes = str_pad($datos[2], 2, "0", STR_PAD_LEFT);
        $numexp = $datos[3];
        $km = $datos[4];
        $sencillos = $datos[5];
        $inciden = 0;
        $gratis = 0;
        $recargo = 0;
        $bonobus = $datos[6];
        $abottes = intval($datos[8])+intval($datos[9]);
        $pasesmun = 0;
        $otros = $datos[10];
        $valman = 0;
        $total = $datos[11];
        //drupal_set_message(t('ingsencillo: @n',array('@n'=>$datos[11])));
        $ingsencillo = $datos[12];
        //drupal_set_message(t('ingsencillo: @n',array('@n'=>$ingsencillo)));
        $ingrecargo = 0;
        $ingtotal = $datos[14];
        $registros[] = array(
          'idconce'=>$conce,
          'anio' => intval($anio),
          'mes'  => intval($mes),
          'nexpe' => intval($numexp),
          'kms' => floatval($km),
          'sencillo' => intval($sencillos),
          'incidencia' => intval($inciden),
          'gratuitos' => intval($gratis),
          'recargo' => intval($recargo),
          'bonobus' => intval($bonobus),
          'abottes' => intval($abottes),
          'pmun' => intval($pasesmun),
          'otros' => intval($otros),
          'valman' => intval($valman),
          'total' => intval($total),
          'ingsencillo' => floatval($ingsencillo),
          'ingrecargo' => floatval($ingrecargo),
          'ingtotal' => floatval($ingtotal),
        );
      }
      }
      $nombrefichero = $conce.'_'.$anio.'_'.$mes.'.JSON';
      $datosjson = array(
        'DatosFicheroProgBase' => array(
          'NombreFichero' => $nombrefichero,
          'Registros' => $registros
        )
      );
      $data = json_encode($datosjson);
      file_put_contents(getcwd().'/sites/default/files/'.$nombrefichero,$data);
      $header = array(
        'Content-Type: application/json',
        'CRTM-SPAI-Auth-Info#Auth-Method:BasicToken',
        'CRTM-SPAI-Auth-Info#User:CEVESA',
        'CRTM-SPAI-Auth-Info#Token:Hd73K4Gd7QnZsrkAUjB89',
        'CRTM-SPAI-Client-Id:CEVESA'
      );
      $crl = curl_init($url);

      curl_setopt($crl, CURLOPT_POST, 1);
      curl_setopt($crl, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($crl, CURLOPT_POSTFIELDS, $data);
      //curl_setopt($crl, CURLOPT_HEADER, array('nemonicRequester'=>'CRTM',));
      curl_setopt($crl, CURLOPT_HTTPHEADER,$header );
      curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
      //curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
      curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
  ;

      $result = curl_exec($crl);
      if ($result === FALSE){
        print_result('ERROR: '.curl_errno($crl).' - '.curl_error($crl),$file->filename,$nombrefichero);
        drupal_set_message(t('Error al Enviar<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" target="_blank">'.$nombrefichero.'.pdf</a>'),'error');
      }else{
        print_result(utf8_decode($result),$file->filename,$nombrefichero);
        drupal_set_message(t('Envío OK<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" download>'.$nombrefichero.'.pdf</a>'));
        drupal_set_message(t('Descargar JSON: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'" download>'.$nombrefichero.'</a>'));
      }
      curl_close($crl);
    }     
  }
  
  /*****************************/
  /*   ENVÍO DE FICHERO VIA    */
  /*****************************/
  
  if (strpos(strtolower($file->filename),"_via")) {
    $url = variable_get('spai_bit_url').'via';
    $fichero = getcwd().'/sites/default/files/'.str_replace('public://','',$file->uri);
    $registros = array();
    $codtit = array(
      'AB1'=>'2501',
      'AB2'=>'2502',
      'AB3'=>'2503',
      'AC1'=>'2504',
      'AC2'=>'2505',
      'AE1'=>'2515',
      'AE2'=>'2516',
      'AX'=>'2517',
      'B1B2'=>'2506',
      'B1B3'=>'2507',
      'B1C1'=>'2508',
      'B1C2'=>'2509',
      'B1E1'=>'2515',
      'B1E2'=>'2516',
      'B1X'=>'2517',
      'B2B2'=>'2131',
      'B2B3'=>'250A',
      'B2C1'=>'250B',
      'B2C2'=>'250C',
      'B2E1'=>'2515',
      'B2E2'=>'2516',
      'B2X'=>'2517',
      'B3B3'=>'2132',
      'B3C1'=>'250D',
      'B3C2'=>'250E',
      'B3E1'=>'2515',
      'B3E2'=>'2516',
      'B3X'=>'2517',
      'C1C1'=>'2133',
      'C1C2'=>'250F',
      'C1E1'=>'2515',
      'C1E2'=>'2516',
      'C1X'=>'2517',
      'C2C2'=>'2514',
      'C2X'=>'2517',
      'E1E1'=>'2517',
      'E1E2'=>'2517',
      'E1X'=>'2517',
      'E2X'=>'2517',
      'E2E2'=>'2517',
      'XX'=>'2517'
    );
    if (($gestor = fopen($fichero, "r")) !== FALSE) {
      while (($datos = fgetcsv($gestor, 1000, ",")) !== FALSE) {
        $anio = $datos[2];
        $mes = str_pad($datos[3], 2, "0", STR_PAD_LEFT);
        $titulo = trim($datos[6]);
        $cate = '0'.$datos[8];
        if(strlen($titulo) < 4){
          switch($titulo){
            case '2':
              $cate = '02';
              break;
            case '5':
              $cate = '03';
              break;
          }
          $titulo = $codtit[$datos[5]];
        }
        $perfil = $datos[7];
        if (strlen($perfil) == 1) $perfil = '0'.$perfil; 
        $registros[] = array(
          'nulinuser'=>substr($datos[0],-3),
          'idsublinea' => substr($datos[1],0,6),
          'anio'  => intval($datos[2]),
          'mes' => intval($datos[3]),
          'dia' => intval($datos[4]),
          'idtipotitulo' => hexdec($titulo),
          'idperfil' => $perfil,
          'idate' => $cate,
          'validaciones' => intval($datos[9])
        );
      }
    }
    switch (substr($file->filename,2,2)){
      case "10":
        $conce = "VCM-503";
        break;
      case "02":
        $conce = "VAC-082";
        break;
      case "03":
        $conce = "VAC-226";
        break;
    }

    $nombrefichero = $conce.'_'.$anio.'_'.$mes.'_VIA.JSON';
    $datosjson = array(
        'DatosFicheroProgVia' => array(
          'NombreFichero' => $nombrefichero,
          'Registros' => $registros
        )
    );
    $data = json_encode($datosjson);
    file_put_contents(getcwd().'/sites/default/files/'.$nombrefichero,$data);
    $header = array(
        'Content-Type: application/json',
        'CRTM-SPAI-Auth-Info#Auth-Method:BasicToken',
        'CRTM-SPAI-Auth-Info#User:CEVESA',
        'CRTM-SPAI-Auth-Info#Token:Hd73K4Gd7QnZsrkAUjB89',
        'CRTM-SPAI-Client-Id:CEVESA'
    );
    $crl = curl_init($url);
    curl_setopt($crl, CURLOPT_POST, 1);
    curl_setopt($crl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($crl, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($crl, CURLOPT_HEADER, array('nemonicRequester'=>'CRTM',));
    curl_setopt($crl, CURLOPT_HTTPHEADER,$header );
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, 0);

    $result = curl_exec($crl);
    if ($result === FALSE){
      print_result(utf8_decode(curl_error($crl)),$file->filename,$nombrefichero);
      drupal_set_message(t('Error al Enviar<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" target="_blank">'.$nombrefichero.'.pdf</a>'),'error');
    }else{
      print_result(utf8_decode($result),$file->filename,$nombrefichero);
      drupal_set_message(t('Envío OK<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" download>'.$nombrefichero.'.pdf</a>'));
      drupal_set_message(t('Descargar JSON: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'" download>'.$nombrefichero.'</a>'));
  }
    curl_close($crl);
  }     
 
  /*****************************/
  /*   ENVÍO DE FICHERO OFERTA */
  /*****************************/
  
  if (strpos(strtolower($file->filename),"_prog.") ||
      strpos(strtolower($file->filename),"_prog_ref") ||
      strpos(strtolower($file->filename),"_real.") ||
      strpos(strtolower($file->filename),"_real_ref")) {
    $url = variable_get('spai_bit_url').'oferta';
    $real = FALSE;
    if (strpos(strtolower($file->filename),"_real")) $real = TRUE;
    $fichero = getcwd().'/sites/default/files/'.str_replace('public://','',$file->uri);
    $registros = array();
    if (($gestor = fopen($fichero, "r")) !== FALSE) {
      if (strpos(strtolower($file->filename),"_prog.")) $tipo = 'PR';
      if (strpos(strtolower($file->filename),"_prog_ref")) $tipo = 'RFP';
      if (strpos(strtolower($file->filename),"_real.")) $tipo = 'RE';
      if (strpos(strtolower($file->filename),"_real_ref")) $tipo = 'RFR';
      $totviaje = 0;
      $conce = 'VCM-503';
      $t_expedi = 0;
      $t_km = 0;
      while (($datos = fgetcsv($gestor, 1000, ",")) !== FALSE) {
        $anio = '20'.$datos[8];
        $mes = str_pad($datos[9],2,"0",STR_PAD_LEFT);
        $dia = str_pad($datos[10],2,"0",STR_PAD_LEFT);
        $fecha = $anio.'-'.$mes.'-'.$dia;
        //drupal_set_message(t('fecha2: @f (@d)',array('@f'=>$fecha, '@d'=>date('l',strtotime($fecha)))));
        switch (date('l',strtotime($fecha))){
          case "Sunday":
            $calend = 'F';
            break;
          case "Monday":
            $calend = 'L';
            break;
          case "Tuesday":
            $calend = 'L';
             break;
          case "Wednesday":
            $calend = 'L';
            break;
          case "Thursday":
            $calend = 'L';
            break;
          case "Friday":
            $calend = 'V';
            break;
          case "Saturday":
            $calend = 'S';
          break;
        }
        $query = db_select('spai_bit_festivos','f')
          ->fields('f',array('fecha'))
          ->condition('fecha',$fecha);
        $result = $query->execute();
        if ($result->rowCount() == 1) $calend = 'F';
        if(($mes == '01' && $dia == '01') ||
          ($mes == '12' && $dia == '25')){
          $tphor = '25';
        }elseif($mes == '12' && ($dia == '24' || $dia == '31')){
          $tphor = '24';
        }elseif($calend=='F' && ($mes == '07' || $mes == '08')){
          $tphor = '9';
        }elseif($calend=='F' && ($mes != '07' && $mes != '08')){
          $tphor = '3';
        }elseif($calend=='S' && ($mes == '07' || $mes == '08')){
          $tphor = '8';
        }elseif($calend=='S' && ($mes != '07' && $mes != '08')){
          $tphor = '2';
        }elseif(($calend=='L' || $calend=='V') && ($mes == '07' || $mes == '08')){
          $tphor = '4';
        }elseif(($calend=='L' || $calend=='V') && ($mes != '07' && $mes != '08')){
          $tphor = '1';
        }
        if ($real) $totviaje = intval($datos[13]);
        $registros[] = array(
          'idconce' => $conce,
          'nulinges' => $datos[2],
          'nulinuser'=> $datos[3],
          'idsublinea' => $datos[4],
          'denominasub' => $datos[5],
          'sentido' => intval($datos[6]),
          'longkms' => floatval($datos[7]),
          'anio'  => intval($anio),
          'mes' => intval($mes),
          'dia' => intval($dia),
          'calend' => $calend,
          'tphor' => $tphor,
          'nexpedi' => intval($datos[11]),
          'kmtsreal' => floatval($datos[12]),
          'totviaje' => $totviaje,
          'tipo' => $tipo
        );
        $t_expedi += intval($datos[11]);
        $t_km += floatval($datos[12]);
      }
    }
    $nombrefichero = $conce.'_'.$anio.'_'.$mes.'_'.$tipo.'.JSON';
    $datosjson = array(
        'DatosFicheroProgOferta' => array(
          'NombreFichero' => $nombrefichero,
          'Registros' => $registros
        )
    );
    $data = json_encode($datosjson);
    file_put_contents(getcwd().'/sites/default/files/'.$nombrefichero,$data);
    $header = array(
        'Content-Type: application/json',
        'CRTM-SPAI-Auth-Info#Auth-Method:BasicToken',
        'CRTM-SPAI-Auth-Info#User:CEVESA',
        'CRTM-SPAI-Auth-Info#Token:Hd73K4Gd7QnZsrkAUjB89',
        'CRTM-SPAI-Client-Id:CEVESA'
    );
    $crl = curl_init($url);
    curl_setopt($crl, CURLOPT_POST, 1);
    curl_setopt($crl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($crl, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($crl, CURLOPT_HEADER, array('nemonicRequester'=>'CRTM',));
    curl_setopt($crl, CURLOPT_HTTPHEADER,$header );
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, 0);

    $result = curl_exec($crl);
    if ($result === FALSE){
      print_result(utf8_decode(curl_error($crl)),$file->filename,$nombrefichero);
      drupal_set_message(t('Error al Enviar<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" target="_blank">'.$nombrefichero.'.pdf</a>'),'error');
    }else{
      print_result(utf8_decode($result),$file->filename,$nombrefichero);
      drupal_set_message(t('Envío OK<br />Descargar resultado: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'.pdf" download>'.$nombrefichero.'.pdf</a>'));
      drupal_set_message(t('Descargar JSON: <a href="https://intranet.cevesa.es/sites/default/files/'.$nombrefichero.'" download>'.$nombrefichero.'</a>'));
      drupal_set_message(t('Expediciones: @e<br />Km: @k',array('@e'=>$t_expedi,'@k'=>$t_km)));
  }
    curl_close($crl);
  }     


  unlink($file->uri);
  $query = db_delete('file_managed')
      ->condition('fid', $file->fid)
      ->execute();
}