<?php
include_once (ROOT . FOLDER_CORE .'/auth.php'); 
if ($auth == 1) {
    $contact_nif = ! empty($uri[4]) ? $uri[4] : '';
    if ($contact_nif != '') {
        $base = consultaContactosClave($bd_conn, $contact_nif);
        if (! empty($base["CODIGO"])) {
            $data = array();
            if ($base["CONTACTO"] == 0) {
                $contact_type = "ORGANIZACIÓN";
            }elseif ($base["CONTACTO"] == 1) {
                $contact_type = "CONTACTO";
            }
            //CARGO EL ARRAY DE CONEXIONES
            $data[$base["NIF"]] = array ( 
                "contact_id" => $base["CODIGO"],
                "contact_type" => $contact_type,
                "contact_name" => mb_strtoupper($base["NOMBRE"], 'UTF-8'),
                "contat_lastname" => mb_strtoupper($base["APELLIDO1"], 'UTF-8'),
                "contat_lastname2" => mb_strtoupper($base["APELLIDO2"], 'UTF-8'),
                "contat_nif" => mb_strtoupper($base["NIF"], 'UTF-8'),
                "contat_direction" => mb_strtoupper($base["DIRECCION_PER"], 'UTF-8'),
                "contat_phone" => $base["TLFNO1"],
                "contat_email" => mb_strtoupper($base["EMAIL1"], 'UTF-8'),
                "contat_direction_org" => mb_strtoupper($base["DIRECCION_TRA"], 'UTF-8')
            );
        }else{
            $data = array();
            $data["document"] = array ( 
                "status" => "message: error",
                "message" => "Contact not found"
            );
        }    
    }else {
        $data = array();
        $data[] = array ( 
            "status" => "error",
            "message" => "NIF is missing"
        );
    }
        header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
}elseif ($auth == 0) {
    $data = array();
    $data[] = array ( 
        "status" => "unauthorized_client",
        "message" => "Invalid authorization token"
    );
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
}
//FUNCIONES=============================================
function consultaContactosClave($bd, $contact_nif)
{
    $sql =  "   SELECT DISTINCT C.CODIGO, C.NOMBRE, C.APELLIDO1, C.APELLIDO2, C.NIF, C.MOSTRAR, C.DIRECCION_PER, C.TLFNO1, C.TLFNO2, C.EMAIL1, C.DIRECCION_TRA, C.CONTACTO, C.ORGANIZACION, C.NOTAS
                FROM CONTACTOS C 
                WHERE C.NIF = ? LIMIT 1";
    $base = $bd->prepare($sql);
    $contact_nif = mysqli_real_escape_string($bd, $contact_nif);
    $base->bind_param('s', $contact_nif);
    $base->execute();
    $result =mysqli_fetch_array($base->get_result());
    $base->close();
    return $result;
}  
?>