<?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\Core\AppBootstrap;
use App\Repositories\QuotationRepository;
use App\Repositories\SalesInvoiceRepository;
use App\Services\QuotationService;
use Throwable;
use App\Modules\Sales\Application\Services\SalesRouteContext;
use App\Controllers\QuotationDispatchController;

final class QuotationController
{
    private \PDO $pdo;
    private QuotationRepository $quotations;
    private QuotationService $service;
    private SalesRouteContext $routeContext;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->quotations = new QuotationRepository($this->pdo);
        $this->service = new QuotationService($this->pdo, $this->quotations, new SalesInvoiceRepository($this->pdo));
        $this->routeContext = new SalesRouteContext();
    }

    public function index(): void
    {
        Auth::requireLogin();
        AppBootstrap::bootQuotations($this->pdo);
        require_permission('quotations.view');

        $q = trim((string) Request::get('q', ''));
        $status = trim((string) Request::get('status', ''));
        $partyId = (int) Request::get('party_id', 0);
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($this->quotations->search($q, $status, $partyId), $page, 25);

        Response::view('pages/quotations/index', [
            'rows' => $pagination['items'],
            'page' => $pagination['page'],
            'per_page' => $pagination['per_page'],
            'total_pages' => $pagination['total_pages'],
            'total_rows' => $pagination['total_rows'],
            'from_row' => $pagination['from'],
            'to_row' => $pagination['to'],
            'customers' => $this->quotations->fetchCustomersCompact(),
            'filters' => ['q' => $q, 'status' => $status, 'party_id' => $partyId],
            'page_title' => 'سجل عروض الأسعار',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'عروض الأسعار'],
                ['label' => 'سجل عروض الأسعار'],
            ],
            'quotations_url' => $this->routeContext->quotationsPath(),
            'quotation_form_url' => $this->routeContext->quotationFormPath(),
            'quotation_view_base_url' => $this->routeContext->quotationViewPath(),
            'quotation_convert_base_url' => $this->routeContext->quotationConvertPath(),
            'quotation_email_base_url' => $this->routeContext->quotationEmailPath(),
            'quotation_whatsapp_base_url' => $this->routeContext->quotationWhatsappPath(),
            'sales_invoice_view_base_url' => $this->routeContext->invoiceViewPath(),
        ]);
    }

    public function form(): void
    {
        Auth::requireLogin();
        AppBootstrap::bootQuotations($this->pdo);

        $id = (int) Request::get('id', 0);
        $isEdit = $id > 0;
        if ($isEdit) {
            require_permission('quotations.edit');
        } else {
            require_permission('quotations.create');
        }

        $errors = [];
        try {
            $form = $this->service->loadForm($id);
        } catch (Throwable $e) {
            http_response_code(404);
            exit('Quotation not found');
        }

        if (Request::isPost()) {
            Csrf::verify();
            try {
                $quotationId = $this->service->save($id, Request::all(), current_user_id() ? (int) current_user_id() : null);
                Response::flash('success', $isEdit ? 'تم تحديث عرض السعر.' : 'تم حفظ عرض السعر بنجاح.');
                Response::redirect($this->routeContext->quotationViewPath($quotationId));
                return;
            } catch (Throwable $e) {
                $errors[] = 'حدث خطأ أثناء الحفظ: ' . $e->getMessage();
                $form = array_merge($form, Request::all());
                $form['party_id'] = (int) Request::post('party_id', $form['party_id'] ?? 0);
                $form['lines'] = $this->buildPostedUiLines();
            }
        }

        Response::view('pages/quotations/form', [
            'form' => $form,
            'customers' => $this->quotations->fetchCustomers(),
            'errors' => $errors,
            'is_edit' => $isEdit,
            'statuses' => ['draft' => 'مسودة', 'sent' => 'مرسل', 'approved' => 'معتمد', 'rejected' => 'مرفوض', 'expired' => 'منتهي', 'converted' => 'تم تحويله'],
            'page_title' => $isEdit ? 'تعديل عرض سعر' : 'إنشاء عرض سعر',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'عروض الأسعار', 'url' => $this->routeContext->quotationsPath()],
                ['label' => $isEdit ? 'تعديل' : 'إنشاء'],
            ],
            'quotations_url' => $this->routeContext->quotationsPath(),
            'quotation_view_url' => $isEdit ? $this->routeContext->quotationViewPath($id) : null,
        ]);
    }

    public function view(): void
    {
        Auth::requireLogin();
        AppBootstrap::bootQuotations($this->pdo);
        require_permission('quotations.view');

        $id = (int) Request::get('id', 0);
        $quotation = $this->quotations->findWithParty($id);
        if (!$quotation) {
            http_response_code(404);
            exit('Quotation not found');
        }

        Response::view('pages/quotations/view', [
            'quotation' => $quotation,
            'lines' => $this->quotations->fetchItems($id),
            'dispatch_logs' => $this->quotations->fetchDispatchLogs($id),
            'page_title' => 'عرض سعر',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'عروض الأسعار', 'url' => $this->routeContext->quotationsPath()],
                ['label' => 'عرض سعر'],
            ],
            'quotations_url' => $this->routeContext->quotationsPath(),
            'quotation_form_url' => $this->routeContext->quotationFormPath(),
            'quotation_convert_url' => $this->routeContext->quotationConvertPath($id),
            'quotation_email_url' => $this->routeContext->quotationEmailPath($id),
            'quotation_whatsapp_url' => $this->routeContext->quotationWhatsappPath($id),
            'sales_invoice_view_base_url' => $this->routeContext->invoiceViewPath(),
        ]);
    }

    public function convert(): void
    {
        Auth::requireLogin();
        AppBootstrap::bootQuotations($this->pdo, true);
        require_permission('quotations.convert');
        require_permission('sales.invoices.create');

        $id = (int) (Request::get('id', Request::post('id', 0)));
        $quotation = $this->quotations->findWithParty($id);
        if (!$quotation) {
            http_response_code(404);
            exit('Quotation not found');
        }
        $lines = $this->quotations->fetchFormItems($id);

        if (Request::isPost()) {
            Csrf::verify();
            try {
                if (strtolower((string) $quotation['status']) === 'converted' && !empty($quotation['converted_invoice_id'])) {
                    Response::flash('warning', 'تم تحويل عرض السعر مسبقًا إلى فاتورة بيع.');
                    Response::redirect($this->routeContext->invoiceViewPath((int) $quotation['converted_invoice_id']));
                    return;
                }
                $invoiceId = $this->service->convertToDraftSalesInvoice($id, current_user_id() ? (int) current_user_id() : null);
                Response::flash('success', 'تم تحويل عرض السعر إلى فاتورة بيع كمسودة.');
                Response::redirect($this->routeContext->invoiceFormPath($invoiceId));
                return;
            } catch (Throwable $e) {
                Response::flash('danger', 'تعذر تحويل عرض السعر: ' . $e->getMessage());
                Response::redirect($this->routeContext->quotationViewPath($id));
                return;
            }
        }

        Response::view('pages/quotations/convert', [
            'quotation' => $quotation,
            'lines' => $lines,
            'page_title' => 'تحويل عرض السعر إلى فاتورة بيع',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'عروض الأسعار', 'url' => $this->routeContext->quotationsPath()],
                ['label' => 'عرض سعر', 'url' => $this->routeContext->quotationViewPath($id)],
                ['label' => 'تحويل إلى فاتورة بيع'],
            ],
            'quotations_url' => $this->routeContext->quotationsPath(),
            'quotation_view_url' => $this->routeContext->quotationViewPath($id),
        ]);
    }

    private function buildPostedUiLines(): array
    {
        $itemIds = Request::post('item_id', []);
        $itemNames = Request::post('item_name', []);
        $qtys = Request::post('qty', []);
        $prices = Request::post('price', []);
        $lineNotes = Request::post('line_notes', []);
        $lines = [];
        $count = max(count($itemIds), count($itemNames), count($qtys), count($prices));
        for ($i = 0; $i < $count; $i++) {
            $qty = (float)($qtys[$i] ?? 0);
            $price = (float)($prices[$i] ?? 0);
            $lines[] = [
                'item_id' => (int)($itemIds[$i] ?? 0),
                'item_name' => (string)($itemNames[$i] ?? ''),
                'qty' => $qty > 0 ? $qty : 1,
                'price' => $price,
                'line_total' => round(max(0, $qty) * max(0, $price), 2),
                'line_notes' => (string)($lineNotes[$i] ?? ''),
            ];
        }
        return $lines ?: [['item_id' => 0, 'item_name' => '', 'qty' => 1, 'price' => 0, 'line_total' => 0, 'line_notes' => '']];
    }
    public function email(): void
    {
        (new QuotationDispatchController())->email();
    }

    public function whatsapp(): void
    {
        (new QuotationDispatchController())->whatsapp();
    }
}
