<?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);
    }

    $mensaje = "El cambio de estado del reclamo fue satisfactorio";
    
    //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
    
    $postdata = file_get_contents("php://input");
    if (isset($postdata)) {
        $request = json_decode($postdata, true);

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

    // Sacar
    $id = $request['id'];
    $user = $request['user_id'];
    $fin_obser = $request['fin_observaciones'];
    $fin_responsable = $request['fin_responsable_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 {

        $fecha_hoy = date("Y-m-d H:i:s");
        
        // Comienzo la transaccion
        mysqli_query($link, "BEGIN");

        $sql  = "UPDATE reclamos_contrato SET fin_fecha = '${fecha_hoy}', fin_observaciones = '$fin_obser', fin_responsable_id = ${fin_responsable} ";
        $sql .= "WHERE id = $id" ;

        $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);
         

        // 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));
        
    }

?>