<?php
   
    //http://stackoverflow.com/questions/18382740/cors-not-working-php
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }
    
    
    const ENTREGADO = 5;
    
    $mensaje = "El cambio de estado del contrato fue satisfactorio";
    
    //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
    $postdata = file_get_contents("php://input");
    
    $myfile = fopen("logFile.txt", "a") or die("Unable to open file!");
    $parametros = print_r($postdata,TRUE);
    fwrite($myfile, "\n");
    fwrite($myfile, "---------------------------". date("Y-m-d H:i:s") ."--------------------------------------------------------");
    fwrite($myfile, "\n");    
    fwrite($myfile, "----------------------------nuevo registro log-------------------------------------------------------");
    fwrite($myfile, "\n");    
    fwrite($myfile, "-----------------------------------------------------------------------------------------------------");
    
    fwrite($myfile, "\n");
    
    fwrite($myfile, $parametros);
    fclose($myfile); 
    if (isset($postdata)) {
        $request = json_decode($postdata, true);

    }
    else {
        exit(0);
    }
    
    require('config.php');

    // Sacar
    $user = $request['user_id'];
    
    $lat = $request['latitud'];
    $long = $request['longitud'];
    $sign = $request['firma'];
    $fecha_hoy = date("Y-m-d H:i:s");
    $contrato = $request['id'];
    
    // Conectar la BD
    $link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die('Error de conexion con base de datos: ' . mysqli_connect_errno());
    mysqli_set_charset($link,'utf8');

    $nuevo_estado = mysqli_real_escape_string($link, $request['estado_id']);
    //$sector = mysqli_real_escape_string($link, $request['sector']);
    
    try {
        
        // Comienzo la transaccion
        mysqli_query($link, "BEGIN");
    
        
        $sql  = "UPDATE contratos_cabecera SET estado_id = ${nuevo_estado} ";
        $sql .= "WHERE id = ${contrato}" ;        

        $myfile = fopen("logFile.txt", "a") or die("Unable to open file!");
        fwrite($myfile, "\n");
        fwrite($myfile, "update");
        fwrite($myfile, "\n");
        fwrite($myfile, $sql);
        fwrite($myfile, "\n");
        fclose($myfile);        

        $result = mysqli_query($link, $sql);
        
        
        $sql =  "INSERT INTO estados_de_contrato (contrato_id, fecha, usuario_id, tipo_estado_id, observaciones, borrado) ";
        $sql .= "VALUES (${contrato}, '$fecha_hoy', $user, $nuevo_estado, '', 0) ";

        $myfile = fopen("logFile.txt", "a") or die("Unable to open file!");
        fwrite($myfile, "\n");
        fwrite($myfile, "update");
        fwrite($myfile, "\n");
        fwrite($myfile, $sql);
        fwrite($myfile, "\n");
        fclose($myfile);        

        $result = mysqli_query($link, $sql);
    
        // Si el contrato se va a entregar
        if ($nuevo_estado == ENTREGADO) {
            // Al entregar un contrato graba posicion y firma del cliente
            $sql  = "UPDATE envios_detalle SET latitud = ${lat}, longitud = ${long}, firma = '${sign}', fecha_envio_real = '${fecha_hoy}' ";
            $sql .= "WHERE contrato_id = ${contrato}" ;
        
            // Ejecuto la consulta
            $result = mysqli_query($link, $sql);
                    $myfile = fopen("logFile.txt", "a") or die("Unable to open file!");
        fwrite($myfile, "\n");
        fwrite($myfile, "update");
        fwrite($myfile, "\n");
        fwrite($myfile, $sql);
        fwrite($myfile, "\n");
        fclose($myfile);        


        }


        // Fin de la transaccion
         mysqli_query($link, "COMMIT");
         
         // Cierro la conexion con la BD
         mysqli_close($link);
         
         // Envia al respuesta
         echo json_encode($mensaje);
         
    } catch(exception $error) {
        mysqli_query($link, "ROLLBACK");
        die(mysqli_error($link));
        
    }

?>