<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Session;
use App\Services\FactureService;
use App\Services\DocumentEngine;
use App\Services\DocumentCycleService;
use App\Services\DocumentManager;
use Throwable;

final class FactureController extends Controller
{
    public function index(): void
    {
        $this->view('factures/index', [
            'title' => 'Factures',
            'factures' => (new FactureService())->list(),
        ]);
    }

    public function createFromBonLivraison(): void
    {
        try {
            $id = (new FactureService())->createFromBonLivraison((int) Request::post('bon_livraison_id', 0));
            (new DocumentCycleService())->log('BL', (int)Request::post('bon_livraison_id', 0), 'FACTURE', 'Facturé', 'FACTURE', $id);
            (new DocumentCycleService())->log('FACTURE', $id, 'CREATION', 'Créée depuis un bon de livraison', 'BL', (int)Request::post('bon_livraison_id', 0));
            Session::flash('success', 'Facture créée depuis le bon de livraison.');
            $this->redirect('factures_show&id=' . $id);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('bons_livraison');
        }
    }


    public function createFromDevis(): void
    {
        $devisId = (int) Request::post('devis_id', 0);
        try {
            $id = (new FactureService())->createFromDevis($devisId);
            (new DocumentCycleService())->log('DEVIS', $devisId, 'FACTURE_DIRECTE', 'Facturé directement', 'FACTURE', $id);
            (new DocumentCycleService())->log('FACTURE', $id, 'CREATION', 'Créée directement depuis un devis', 'DEVIS', $devisId);
            Session::flash('success', 'Facture créée directement depuis le devis.');
            $this->redirect('factures_show&id=' . $id);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('devis_show&id=' . $devisId);
        }
    }

    public function pdf(): void
    {
        try {
            $data = (new FactureService())->findWithDetails((int) Request::get('id', 0));
            (new DocumentEngine())->streamFacture($data['facture'], $data['lignes']);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('factures');
        }
    }

    public function show(): void
    {
        try {
            $data = (new FactureService())->findWithDetails((int) Request::get('id', 0));
            $this->view('factures/show', [
                'title' => 'Facture ' . $data['facture']['numero'],
                'facture' => $data['facture'],
                'lignes' => $data['lignes'],
                'encaissements' => $data['encaissements'],
                'cycleLinks' => ($cycle = new DocumentCycleService())->links('FACTURE', (int)$data['facture']['id']),
                'cycleHistory' => $cycle->forDocument('FACTURE', (int)$data['facture']['id']),
                'cycleStatus' => $cycle->status('FACTURE', $data['facture'], $cycle->links('FACTURE', (int)$data['facture']['id'])),
            ]);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('factures');
        }
    }

    public function edit(): void
    {
        $factureId = (int) Request::get('id', 0);
        try {
            $documentId = (new DocumentManager())->ensureLegacyInvoiceDocument($factureId);
            $this->redirect('documents_edit&id=' . $documentId);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('factures_show&id=' . $factureId);
        }
    }
}
