<?php

declare(strict_types=1);

namespace App\Modules\Administration\Controllers;

use App\Controllers\Controller;
use App\Modules\Administration\Services\AuthenticationService;
use App\Modules\Administration\Services\AuthorizationService;
use App\Modules\Administration\Services\EmployeeTransferService;
use System\Http\Request;
use System\View\View;

final class EmployeeTransferController extends Controller
{
    public function __construct(
        private AuthenticationService $authentication,
        private AuthorizationService $authorization,
        private EmployeeTransferService $transferService,
        private Request $request,
        View $view
    ) {
        parent::__construct($view);
    }

    private function protect(): void
    {
        if (!$this->authentication->check()) {
            header('Location: /public/login');
            exit;
        }
    }

    private function requireAdministrator(): void
    {
        if (!$this->authorization->isAdministrator()) {
            header('Location: /public/403');
            exit;
        }
    }

    public function store(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $employeeId = (int) $this->request->input(
            'employee_id',
            0
        );

        try {
            $document =
                $_FILES['document_file']
                ?? null;

            $this->transferService->create(
                $employeeId,
                $this->request->all(),
                $document
            );

            header(
                'Location: /public/employees/show?id='
                . $employeeId
                . '&transfer_created=1'
            );

            exit;

        } catch (\Throwable $exception) {
            header(
                'Location: /public/employees/show?id='
                . $employeeId
                . '&transfer_error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }
public function update(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    $employeeId =
        (int) $this->request->input(
            'employee_id',
            0
        );

    try {
        $document =
            $_FILES['document_file']
            ?? null;

        $this->transferService->update(
            $id,
            $this->request->all(),
            $document
        );

        header(
            'Location: /public/employees/show?id='
            . $employeeId
            . '&transfer_updated=1'
        );

        exit;

    } catch (\Throwable $exception) {
        header(
            'Location: /public/employees/show?id='
            . $employeeId
            . '&transfer_error='
            . urlencode(
                $exception->getMessage()
            )
        );

        exit;
    }
}
    public function toggleStatus(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        $employeeId = (int) $this->request->input(
            'employee_id',
            0
        );

        try {
            $this->transferService
                ->toggleStatus($id);

            header(
                'Location: /public/employees/show?id='
                . $employeeId
                . '&transfer_status_updated=1'
            );

            exit;

        } catch (\Throwable $exception) {
            header(
                'Location: /public/employees/show?id='
                . $employeeId
                . '&transfer_error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

    public function viewDocument(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        $transfer =
            $this->transferService->find($id);

        if ($transfer === null) {
            http_response_code(404);

            exit(
                'Transfer record not found.'
            );
        }

        if (
            (int) (
                $transfer['status']
                ?? 0
            ) !== 1
        ) {
            http_response_code(403);

            exit(
                'Transfer record is inactive.'
            );
        }

        $relativePath = (string) (
            $transfer['document_file_path']
            ?? ''
        );

        if ($relativePath === '') {
            http_response_code(404);

            exit(
                'Transfer document is not available.'
            );
        }

        $filePath =
            PUBLIC_PATH
            . '/'
            . ltrim(
                $relativePath,
                '/'
            );

        if (
            !is_file($filePath)
            || !is_readable($filePath)
        ) {
            http_response_code(404);

            exit(
                'Transfer document file not found.'
            );
        }

        $mimeType = (string) (
            $transfer['document_mime_type']
            ?? 'application/octet-stream'
        );

        $originalName = (string) (
            $transfer['document_original_name']
            ?? basename($filePath)
        );

        $safeName = str_replace(
            [
                '"',
                "\r",
                "\n"
            ],
            '',
            $originalName
        );

        header(
            'Content-Type: '
            . $mimeType
        );

        header(
            'Content-Length: '
            . filesize($filePath)
        );

        header(
            'Content-Disposition: inline; filename="'
            . $safeName
            . '"'
        );

        header(
            'X-Content-Type-Options: nosniff'
        );

        readfile($filePath);

        exit;
    }
}