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

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

    include '../jquery/comunes_php/Log.class.php'; 
    $log = new Log("app_trace", "./");
    // 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');

    $contrato = mysqli_real_escape_string($link, $_REQUEST['contrato']);
    
    $orden = " ORDER BY rc.inicio_fecha";

    $sql =  "SELECT rc.id, rc.contrato_id, tr.nombre as tipo_reclamos, tr.prioridad, rc.inicio_fecha, " 
            .   "rc.inicio_responsable_id, rc.inicio_observaciones, rc.fin_fecha, "
            .   "rc.fin_responsable_id, rc.fin_observaciones, u.nombre "
        .   "FROM reclamos_contrato rc, tipo_reclamos tr, usuarios u "
        .   "WHERE rc.tipo_reclamo_id = tr.id "
        .   "AND rc.inicio_responsable_id = u.id "
        .   "AND rc.fin_fecha is NULL "
        .   "AND rc.contrato_id = $contrato";
        
    $sql .= $orden;

    $result = mysqli_query($link, $sql);
    $log->insert($sql, false, false, false);
 
    // die if SQL statement failed
    if (!$result) 
    {
        http_response_code(404);
        echo '';
        die(mysqli_error($link));
    }
    else
    {
        $items = array();
        
        while($row = mysqli_fetch_object($result)){
            array_push($items, $row);
        }
        
        
        //echo json_encode($items, JSON_NUMERIC_CHECK);
        echo json_encode($items);

    }
    mysqli_close($link);
   
 
?>