<?php 

$host_name = 'localhost';
$database = 'previewacd';
$user_name ='previewacd';
$password = '336J#fl6u';
/*conectar bdd local*/$link = mysqli_connect($host_name, $user_name, $password, $database);
if ($link->connect_error) {die("Connection failed: " . $link->connect_error);}else{/*echo "Connected successfully";/**/}


/*/ Your SQL query
$idplan_logfver =  29;//17 28 o 29 ambos;
$sql = "SELECT nom_plano, archivo FROM log_plano_gf WHERE id_log_plano_gf = '".$idplan_logfver."'";

$ejecutarquery=mysqli_query($link,$sql);
if(mysqli_num_rows($ejecutarquery) > 0) {
    $row = mysqli_fetch_assoc($ejecutarquery);
    $nombre_archivo = $row['nom_plano'];
    $archivo_hex = $row['archivo'];  // Assuming this is the hex data
    $archivo = hex2bin(substr($archivo_hex, 2));  // Converting hex to binary, omitting the first "0x"
    
    $info = new SplFileInfo($nombre_archivo);
    $tipo = strtoupper($info->getExtension()); // Converted to upper case for easier comparison

    // Setting the content type header
    if (in_array($tipo, ['PDF', 'DOCX', 'XLSX', 'DOC', 'XLS'])) {
        header('Content-type: application/'.$tipo);
    } else {
        header('Content-type: image/'.$tipo);
    }
    
    echo $archivo;
} else {
	echo "no encontrado id:<br />".$sql;

	if(!$ejecutarquery) {
		echo "<br />Query Error: " . mysqli_error($link);
	}
}

/* Importar/**/
// File path

$file_path = './requerimientos.pdf';

// Check if the file exists
if (file_exists($file_path)) {
    // Read the file into a binary string
    $binary_data = file_get_contents($file_path);

    // Convert the binary string to hex
    $hex_data =  bin2hex($binary_data);//no te deja meterlo si no es en hex

    // SQL query to insert the hex data into the database
    $sql = "INSERT INTO log_plano_gf (archivo) VALUES ('0x".$hex_data."')";

    // Run the query
    $ejecutarquery = mysqli_query($link, $sql);

    // Check query success
    if (mysqli_affected_rows($link) > 0) {
        echo  "Successfully inserted into the database<br />";
		echo $hex_data;
    } else {
        echo "Failed to insert into the database";
    }
} else {
    echo "File does not exist";
}

/**/