<?php
// This script handles the file download and logs the action to the database.

// Start the session to access user info
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../config.php';
require_once '../includes/auth.php'; // Make sure your auth.php includes a redirect_if_not_logged_in or similar function

// --- 1. Get User and Datasource IDs ---
// Ensure the user is logged in
redirect_if_not_logged_in('../login.php');

// Get the user's person_id from the session
$person_id = $_SESSION['person_id'];

// Get the datasource_id from the URL parameter
$datasource_id = $_GET['dspsds_id'] ?? null;

// Validate the datasource_id
if (!$datasource_id || !filter_var($datasource_id, FILTER_VALIDATE_INT)) {
    die("Invalid or missing datasource ID.");
}

// --- 2. Log the Download Action ---
// This code inserts a new record for every download.
try {
    $sql_insert = "
        INSERT INTO dsps_tbl_datasource_used
            (fkdspsdsused_id, fkisp_id_of, dspsdspused_action)
        VALUES
            (?, ?, ?)
    ";
    $stmt_insert = $pdo->prepare($sql_insert);
    $action = "Downloaded";
    $stmt_insert->execute([$datasource_id, $person_id, $action]);

} catch (PDOException $e) {
    // We now log the error and set a user-facing message
    error_log("Error logging download: " . $e->getMessage());
    // Redirect with an error message, but still try to serve the file
    set_message("An error occurred while logging the download.", "danger");
    // We do not die here, as we still want to try and serve the file
}

// --- 3. Retrieve File Path and Name ---
$file_path = null;
$file_name = null;
try {
    $sql_select = "
        SELECT dspsds_filename, dspsds_title_en
        FROM dsps_tbl_datasource
        WHERE pkdspsds_id = ?
    ";
    $stmt = $pdo->prepare($sql_select);
    $stmt->execute([$datasource_id]);
    $row = $stmt->fetch();

    if ($row) {
        $file_name = $row['dspsds_filename'];
        $download_label = $row['dspsds_title_en'] ?: 'datasource_' . $datasource_id;
    }
} catch (PDOException $e) {
    error_log("Error retrieving file info: " . $e->getMessage());
    die("An error occurred while retrieving file information.");
}

if (empty($file_name)) {
    die("File not found in the database.");
}

// Handle external URLs
if (preg_match('/^https?:\\/\\//i', $file_name)) {
    header('Location: ' . $file_name);
    exit;
}

$uploadsDir = realpath(__DIR__ . '/../uploads/datasources');
if (!$uploadsDir) {
    error_log('Uploads directory not found for download.');
    die('File storage directory is unavailable.');
}

$file_path = $uploadsDir . '/' . $file_name;

// --- 4. Serve the File to the User ---
// Check if the file exists on the server
if (file_exists($file_path)) {
    // Set headers to force a download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($download_label . '_' . $file_name) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file_path));

    // Clear output buffer
    if (ob_get_level()) {
        ob_clean();
    }
    flush();

    // Read the file and send it to the output buffer
    readfile($file_path);
    exit;
} else {
    die("The file could not be found on the server at the specified path.");
}
?>
