<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Session;
use App\Models\Document;
use App\Services\DocumentManager;
use App\Services\DocumentEngine;

final class AvoirController extends Controller
{
    public function index(): void
    {
        $model = new Document();
        $filters = [
            'type' => 'AVOIR',
            'q' => trim((string)($_GET['q'] ?? '')),
        ];

        $this->view('avoirs/index', [
            'title' => 'Avoirs',
            'documents' => $model->all($filters),
            'filters' => $filters,
            'documentManager' => new DocumentManager(),
        ]);
    }

    public function pdf(): void
    {
        $id = (int)($_GET['id'] ?? 0);
        $model = new Document();
        $avoir = $model->find($id);

        if (!$avoir || strtoupper((string)$avoir['type_document']) !== 'AVOIR') {
            $this->view('errors/404', ['title' => 'Avoir introuvable']);
            return;
        }

        (new DocumentEngine())->streamAvoir($avoir, $model->lines($id));
    }

    public function create(): void
    {
        $factureId = (int)($_GET['facture_id'] ?? 0);
        $model = new Document();
        $facture = $model->find($factureId);

        if (!$facture || strtoupper((string)$facture['type_document']) !== 'FACTURE') {
            $this->view('errors/404', ['title' => 'Facture introuvable']);
            return;
        }

        $this->view('avoirs/form', [
            'title' => 'Créer un avoir',
            'facture' => $facture,
            'lines' => $model->lines($factureId),
            'numero' => (new DocumentManager())->nextNumber('AVOIR'),
        ]);
    }

    public function store(): void
    {
        $factureId = (int)($_POST['facture_id'] ?? 0);

        try {
            $manager = new DocumentManager();
            $avoirId = $manager->createAvoirFromFacture(
                $factureId,
                (string)($_POST['avoir_type'] ?? 'COMMERCIAL'),
                (string)($_POST['motif'] ?? ''),
                $_POST['lignes'] ?? [],
                (string)($_POST['observations'] ?? '')
            );

            Session::set('success', 'Avoir créé avec succès.');
            $this->redirect('documents_show&id=' . $avoirId);
        } catch (\Throwable $exception) {
            Session::set('error', $exception->getMessage());
            $this->redirect('avoirs_create&facture_id=' . $factureId);
        }
    }
}
