<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Session;
use App\Services\DevisService;
use App\Services\DocumentMailHistoryService;
use App\Services\DocumentMailService;
use Throwable;

final class DocumentCenterController extends Controller
{
    public function prepareDevis(): void
    {
        try {
            $id = (int)Request::get('id', 0);
            $data = (new DevisService())->findWithLines($id);
            $defaults = (new DocumentMailService())->defaults(
                'DEVIS',
                $data['devis']
            );

            $this->view('document_center/send', [
                'title' => 'Envoyer le devis ' . $data['devis']['numero'],
                'documentType' => 'DEVIS',
                'document' => $data['devis'],
                'defaults' => $defaults,
                'sendRoute' => 'document_center_devis_send',
                'returnRoute' => 'devis_show&id=' . $id,
            ]);
        } catch (Throwable $exception) {
            Session::flash('error', $exception->getMessage());
            $this->redirect('devis');
        }
    }

    public function sendDevis(): void
    {
        $id = (int)Request::post('id', 0);

        try {
            $data = (new DevisService())->findWithLines($id);
            $recipient = trim((string)Request::post('recipient', ''));
            $subject = trim((string)Request::post('subject', ''));
            $message = trim((string)Request::post('message', ''));
            $copySender = (int)Request::post('copy_sender', 0) === 1;

            $result = (new DocumentMailService())->sendDocument(
                'DEVIS',
                $data['devis'],
                $data['lignes'],
                $recipient,
                $subject,
                $message,
                $copySender
            );

            (new DocumentMailHistoryService())->record(
                'DEVIS',
                $id,
                (string)$data['devis']['numero'],
                $recipient,
                $subject
            );

            Session::flash(
                'success',
                'Devis envoyé avec succès à ' . $result['recipient'] . '.'
            );
        } catch (Throwable $exception) {
            Session::flash(
                'error',
                'Envoi impossible : ' . $exception->getMessage()
            );
        }

        $this->redirect('devis_show&id=' . $id);
    }
}
