<?php

// data_user/process_request_permission.php
// This script handles the submission of data access permission requests.

// Enable detailed error reporting for debugging purposes
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start a session if one is not already active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if the request method is POST. If not, redirect to prevent direct access.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Redirect to the home page or an error page
    header('Location: ../index.php');
    exit;
}

// Use __DIR__ to get the absolute path to this file's directory,
// ensuring the path to the required files is always correct.
require_once(__DIR__ . '/../config.php');
require_once(__DIR__ . '/../includes/auth.php'); // Not strictly needed, but good practice
require_once(__DIR__ . '/../classes/Permission.php');
require_once(__DIR__ . '/../classes/User.php');

/**
 * Handles the upload of a proof document.
 *
 * @param array|null $file The uploaded file array from $_FILES.
 * @param int $personId The requesting user's person ID to help namespace the file.
 * @return string Relative path (within uploads) to the stored file.
 */
function handle_proof_upload(?array $file, int $personId): string {
    if ($file === null || ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        set_and_redirect('Please upload a PDF proof document for your request.', 'danger');
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        set_and_redirect('There was a problem uploading your proof document. Please try again.', 'danger');
    }

    $maxSize = 10 * 1024 * 1024; // 10 MB
    if (($file['size'] ?? 0) > $maxSize) {
        set_and_redirect('Proof files must be smaller than 10 MB.', 'danger');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file['tmp_name']) ?: '';
    if ($mimeType !== 'application/pdf') {
        set_and_redirect('Only PDF files are accepted as proof.', 'danger');
    }

    $uploadDir = __DIR__ . '/../uploads/permission_proofs';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true)) {
        set_and_redirect('Unable to create the proof upload directory. Contact an administrator.', 'danger');
    }

    if (!is_writable($uploadDir)) {
        set_and_redirect('The proof upload directory is not writable. Contact an administrator.', 'danger');
    }

    $random = bin2hex(random_bytes(8));
    $filename = sprintf('%d_%s.pdf', $personId, $random);
    $destination = $uploadDir . '/' . $filename;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        set_and_redirect('Failed to store your proof document. Please try again.', 'danger');
    }

    return 'permission_proofs/' . $filename;
}

// A helper function to set a session message and redirect
function set_and_redirect($message, $type, $page = 'browse_datasources.php') {
    $_SESSION['message'] = $message;
    $_SESSION['message_type'] = $type;
    // Check if headers have already been sent.
    // This is the most common reason for redirects to fail.
    if (headers_sent()) {
        echo "<div class='alert alert-danger'>Redirect failed. Headers already sent. Please go back to <a href='$page'>the previous page</a> to view the message.</div>";
        echo "Message: " . htmlspecialchars($message);
        exit;
    } else {
        header('Location: ' . $page);
        exit;
    }
}

// 1. Check if the user is logged in
if (!isset($_SESSION['person_id']) || !isset($_SESSION['user_id'])) {
    set_and_redirect('You must be logged in to request permission.', 'danger');
}

$user_id = $_SESSION['user_id'];
$person_id = $_SESSION['person_id'];

// 2. Validate and sanitize POST data
$dataSourceId = filter_input(INPUT_POST, 'data_source_id', FILTER_VALIDATE_INT);

// Replace deprecated FILTER_SANITIZE_STRING
$permissionType = trim(filter_input(INPUT_POST, 'permission_type', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
$notes = trim(filter_input(INPUT_POST, 'notes', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));

// Check if required fields are missing or invalid
if (!$dataSourceId || empty($permissionType) || empty($notes)) {
    set_and_redirect('Invalid or missing request details. Please try again.', 'danger');
}

$proofPath = handle_proof_upload($_FILES['proof_file'] ?? null, $person_id);

// 3. Instantiate the Permission class and process the request
try {
    $permissionManager = new Permission($pdo);

    // Check if a similar request (for the same user, DS, and type) already exists.
    $existingRequest = $permissionManager->getPendingRequest($person_id, $dataSourceId, $permissionType);

    if ($existingRequest) {
        set_and_redirect('A request for this permission type is already pending.', 'warning');
    }

    // Attempt to add the new permission request to the database.
    $success = $permissionManager->addPermissionRequest(
        $person_id,
        $dataSourceId,
        $permissionType,
        'Pending', // Set status to Pending
        $notes,
        $proofPath
    );

    if ($success) {
        set_and_redirect('Your request for ' . htmlspecialchars($permissionType) . ' access has been submitted successfully.', 'success');
    } else {
        set_and_redirect('Failed to submit your request. Please try again later.', 'danger');
    }

} catch (Exception $e) {
    // Log the detailed error for debugging, but show a generic message to the user.
    error_log("Error submitting permission request: " . $e->getMessage());
    set_and_redirect('An unexpected error occurred. Please try again.', 'danger');
}

?>
