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

    $perfil = mysqli_real_escape_string($link, $_REQUEST['perfil']);

    $sql = 	"select cd.contrato_id as contrato, cd.fecha_fin, fa.nombre as fabrica, pr.nombre as producto, cda.adicional_id, ad.nombre as adicional "
    	.	"from contratos_cabecera cc, contratos_detalle cd, contrato_detalle_adicionales cda, productos pr, adicionales ad, fabricas fa "
    	.	"where cd.contrato_id = cc.id "
    	.	"and   cc.estado_id in (3, 4) "
    	.	"and   cd.contrato_id = cda.contrato_id "
    	.	"and   cd.renglon_id = cda.renglon_id "
    	.	"and   cd.producto_id = pr.id "
    	.	"and   cda.adicional_id = ad.id "
    	.	"and   cd.fabrica_id = fa.id "
    	.	"order by cd.contrato_id, cd.renglon_id, cd.fecha_fin, cd.producto_id, cda.adicional_id" ;

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