<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || $_SESSION['role'] === 'guest') {
    header("Location: login.php");
    exit;
}

if (
    !isset($_GET['id']) || !is_numeric($_GET['id']) ||
    !isset($_GET['document_id']) || !is_numeric($_GET['document_id'])
) {
    die("Invalid request.");
}

$file_id = (int) $_GET['id'];
$document_id = (int) $_GET['document_id'];
$user_id = (int) ($_SESSION['user_id'] ?? 0);
$company_id = isset($_SESSION['company_id']) && $_SESSION['company_id'] !== ''
    ? (int) $_SESSION['company_id']
    : null;

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

/*
|--------------------------------------------------------------------------
| Load file with ownership check
|--------------------------------------------------------------------------
| Personal user  => d.user_id = :user_id
| Company user   => d.company_id = :company_id
*/
if ($company_id !== null) {
    $stmt = $db->prepare("
        SELECT df.*, d.company_id
        FROM document_files df
        INNER JOIN documents d ON df.document_id = d.id
        WHERE df.id = :file_id
          AND df.document_id = :document_id
          AND d.company_id = :company_id
        LIMIT 1
    ");
    $stmt->bindValue(":file_id", $file_id, PDO::PARAM_INT);
    $stmt->bindValue(":document_id", $document_id, PDO::PARAM_INT);
    $stmt->bindValue(":company_id", $company_id, PDO::PARAM_INT);
} else {
    $stmt = $db->prepare("
        SELECT df.*, d.user_id
        FROM document_files df
        INNER JOIN documents d ON df.document_id = d.id
        WHERE df.id = :file_id
          AND df.document_id = :document_id
          AND d.user_id = :user_id
        LIMIT 1
    ");
    $stmt->bindValue(":file_id", $file_id, PDO::PARAM_INT);
    $stmt->bindValue(":document_id", $document_id, PDO::PARAM_INT);
    $stmt->bindValue(":user_id", $user_id, PDO::PARAM_INT);
}

$stmt->execute();
$file = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$file) {
    die("File not found or access denied.");
}

/*
|--------------------------------------------------------------------------
| Delete file record
|--------------------------------------------------------------------------
*/
$delete = $db->prepare("
    DELETE FROM document_files
    WHERE id = :file_id
      AND document_id = :document_id
");
$delete->bindValue(":file_id", $file_id, PDO::PARAM_INT);
$delete->bindValue(":document_id", $document_id, PDO::PARAM_INT);

if ($delete->execute() && $delete->rowCount() > 0) {
    if (!empty($file['file_path'])) {
        $fullPath = __DIR__ . "/" . $file['file_path'];
        if (is_file($fullPath)) {
            @unlink($fullPath);
        }
    }
}

header("Location: edit_document.php?id=" . $document_id);
exit;