<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Repositories\QuotationDispatchRepository;
use App\Services\QuotationDispatchService;
use App\Modules\Sales\Application\Services\SalesRouteContext;
use InvalidArgumentException;
use Throwable;

final class QuotationDispatchController
{
    private QuotationDispatchService $service;
    private SalesRouteContext $routeContext;

    public function __construct()
    {
        $pdo = DB::pdo();
        $this->service = new QuotationDispatchService($pdo, new QuotationDispatchRepository($pdo));
        $this->routeContext = new SalesRouteContext();
    }

    public function email(): void
    {
        Auth::requireLogin();
        require_permission('quotations.send');
        $id = Request::int('id');
        try {
            $quotation = $this->service->quotation($id);
        } catch (Throwable $e) {
            http_response_code(404);
            exit($e->getMessage());
        }
        $form = $this->service->defaultEmailForm($quotation);
        $errors = [];

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $form = array_merge($form, Request::all());
                $this->service->sendEmail($id, Request::all());
                Response::flash('success', 'تم إرسال البريد بنجاح.');
                Response::redirect($this->routeContext->quotationViewPath($id));
                return;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
                $form = array_merge($form, Request::all());
            }
        }

        Response::view('pages/quotations/send_email', [
            'quotation' => $quotation,
            'form' => $form,
            'errors' => $errors,
            'page_title' => 'إرسال عرض السعر بالبريد',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'عروض الأسعار', 'url' => $this->routeContext->quotationsPath()],
                ['label' => 'عرض سعر', 'url' => $this->routeContext->quotationViewPath($id)],
                ['label' => 'إرسال بالبريد'],
            ],
            'quotation_view_url' => $this->routeContext->quotationViewPath($id),
        ]);
    }

    public function whatsapp(): void
    {
        Auth::requireLogin();
        require_permission('quotations.send');
        $id = Request::int('id');
        try {
            $quotation = $this->service->quotation($id);
            header('Location: ' . $this->service->whatsappUrl($id, $quotation));
            exit;
        } catch (InvalidArgumentException $e) {
            Response::flash('error', $e->getMessage());
            Response::redirect($this->routeContext->quotationViewPath($id));
            return;
        } catch (Throwable $e) {
            http_response_code(404);
            exit($e->getMessage());
        }
    }
}
