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

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

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

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

$user_id = (int)($_SESSION['user_id'] ?? 0);

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

$id = (int)$_GET['id'];

$workspace_type = $_GET['workspace'] ?? 'personal';
$requested_company_id = (int)($_GET['company_id'] ?? 0);

$is_company_workspace = false;
$active_company_id = null;

if ($workspace_type === 'company' && $requested_company_id > 0) {
    $stmtCompany = $db->prepare("
        SELECT c.id
        FROM company_users cu
        INNER JOIN companies c ON c.id = cu.company_id
        WHERE cu.user_id = :user_id
          AND cu.company_id = :company_id
        LIMIT 1
    ");
    $stmtCompany->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $stmtCompany->bindValue(':company_id', $requested_company_id, PDO::PARAM_INT);
    $stmtCompany->execute();

    $companyRow = $stmtCompany->fetch(PDO::FETCH_ASSOC);

    if ($companyRow) {
        $is_company_workspace = true;
        $active_company_id = (int)$companyRow['id'];
    }
}

try {
    if ($is_company_workspace) {
        $stmt = $db->prepare("
            UPDATE documents
            SET is_deleted = 1,
                deleted_at = NOW(),
                updated_by = :updated_by
            WHERE id = :id
              AND company_id = :company_id
              AND is_deleted = 0
            LIMIT 1
        ");
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
        $stmt->bindValue(':updated_by', $user_id, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            UPDATE documents
            SET is_deleted = 1,
                deleted_at = NOW(),
                updated_by = :updated_by
            WHERE id = :id
              AND user_id = :user_id
              AND company_id IS NULL
              AND is_deleted = 0
            LIMIT 1
        ");
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->bindValue(':updated_by', $user_id, PDO::PARAM_INT);
    }

    $stmt->execute();

    if ($stmt->rowCount() <= 0) {
        die("Document not found or already deleted.");
    }
} catch (Exception $e) {
    die("Delete failed.");
}

$redirect = "my_documents.php?workspace=" . urlencode($is_company_workspace ? 'company' : 'personal')
          . "&scope=" . urlencode($is_company_workspace ? 'company' : 'personal');

if ($is_company_workspace && !empty($active_company_id)) {
    $redirect .= "&company_id=" . (int)$active_company_id;
}

header("Location: " . $redirect);
exit;