<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Attachment;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class AttachmentsController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    private function tenantId(): int { return (int) ($_SESSION['tenant_id'] ?? 0); }
    private function userId():   int { return (int) (Session::user()['user_id'] ?? 0); }

    private function ownerReturnPath(string $ownerType, int $ownerId): string
    {
        return match ($ownerType) {
            'asset'      => "/Assets/show/{$ownerId}",
            'incident'   => "/Incidents/show/{$ownerId}",
            'work_order' => "/WorkOrders/show/{$ownerId}",
            'expense'    => "/Expenses/show/{$ownerId}",
            default      => '/Home',
        };
    }

    public function upload(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Home');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Home');

        $ownerType = (string) ($_POST['owner_type'] ?? '');
        $ownerId   = (int) ($_POST['owner_id'] ?? 0);
        if (!in_array($ownerType, Attachment::OWNERS, true) || $ownerId <= 0) {
            Session::flash('attach_msg', 'Invalid attachment target.');
            redirect('/Home');
        }

        if (empty($_FILES['file'])) {
            Session::flash('attach_msg', 'No file uploaded.');
            redirect($this->ownerReturnPath($ownerType, $ownerId));
        }

        try {
            $stored = Attachment::moveUploaded($ownerType, $_FILES['file']);
            Attachment::create($this->tenantId(), $this->userId(), $ownerType, $ownerId, $stored, $_POST['caption'] ?? null);
            Session::flash('attach_msg', 'File uploaded.');
        } catch (\Throwable $e) {
            Session::flash('attach_msg', 'Upload failed: ' . $e->getMessage());
        }
        redirect($this->ownerReturnPath($ownerType, $ownerId));
    }

    public function delete(int $id): void
    {
        $att = Attachment::findInTenant($this->tenantId(), $id);
        if ($att) {
            Attachment::softDelete($this->tenantId(), $id);
            Session::flash('attach_msg', 'Attachment removed.');
            redirect($this->ownerReturnPath($att['owner_type'], (int) $att['owner_id']));
        }
        redirect('/Home');
    }

    public function download(int $id): void
    {
        $att = Attachment::findInTenant($this->tenantId(), $id);
        if (!$att) { http_response_code(404); echo 'Not found'; return; }
        $path = Attachment::absolutePath($att['file_name']);
        if (!is_file($path)) { http_response_code(404); echo 'File missing'; return; }
        header('Content-Type: ' . ($att['mime_type'] ?: 'application/octet-stream'));
        header('Content-Length: ' . filesize($path));
        header('Content-Disposition: inline; filename="' . rawurlencode($att['original_name']) . '"');
        readfile($path);
    }
}
