<?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\SalesReturnRepository;
use App\Services\SalesReturnService;
use Throwable;
use App\Modules\Sales\Application\Services\SalesRouteContext;

final class SalesReturnController
{
    private \PDO $pdo;
    private SalesReturnRepository $returns;
    private SalesReturnService $service;
    private SalesRouteContext $routeContext;

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

    private function ensureSchema(): bool
    {
        if (!table_exists($this->pdo, 'sales_returns')) {
            Response::view('pages/dashboard', ['error' => 'مطلوب تشغيل ملف التحديث: sql/phase_09_sales_returns_phase1.sql']);
            return false;
        }
        return true;
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('sales_returns.view');
        if (!$this->ensureSchema()) return;

        $q = trim((string) Request::get('q', ''));
        $status = trim((string) Request::get('status', ''));
        $dateFrom = trim((string) Request::get('from', ''));
        $dateTo = trim((string) Request::get('to', ''));
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($this->returns->search($q, $status, $dateFrom, $dateTo), $page, 25);

        Response::view('pages/sales/returns_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'],
            'q' => $q,
            'status' => $status,
            'from' => $dateFrom,
            'to' => $dateTo,
            'page_title' => 'مرتجعات البيع',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'المبيعات', 'url' => $this->routeContext->salesBoardPath()],
                ['label' => 'مرتجعات البيع'],
            ],
            'sales_invoices_url' => $this->routeContext->invoicesPath(),
            'sales_returns_url' => $this->routeContext->returnsPath(),
            'sales_return_view_base_url' => $this->routeContext->returnViewPath(),
        ]);
    }

    public function form(): void
    {
        Auth::requireLogin();
        require_permission('sales_returns.create');
        if (!$this->ensureSchema()) return;

        $returnId = (int) Request::get('id', 0);
        $sourceInvoiceId = (int) Request::get('invoice_id', 0);
        try {
            $form = $this->service->loadForm($returnId, $sourceInvoiceId);
        } catch (Throwable $e) {
            $msg = (string)$e->getMessage();
            if ($msg === 'Not found' || $msg === 'Invoice not found' || $msg === 'invoice_id required') {
                http_response_code($msg === 'invoice_id required' ? 400 : 404);
                exit($msg);
            }
            Response::flash('danger', $msg);
            Response::redirect($this->routeContext->invoiceViewPath($sourceInvoiceId));
            return;
        }

        if (Request::isPost()) {
            Csrf::verify();
            $form = $this->service->applyPostedInput($form, Request::all());
            if (!$form['errors']) {
                try {
                    $savedId = $this->service->saveDraft($returnId, $form, current_user_id() ? (int) current_user_id() : 0);
                    Response::flash('success', 'تم حفظ مرتجع البيع كمسودة.');
                    Response::redirect($this->routeContext->returnViewPath($savedId));
                    return;
                } catch (Throwable $e) {
                    if ($e->getMessage() !== 'validation') {
                        $form['errors'][] = 'حدث خطأ أثناء الحفظ: ' . $e->getMessage();
                    }
                }
            }
        }

        Response::view('pages/sales/return_form', $form + [
            'page_title' => $form['isEdit'] ? 'تعديل مرتجع بيع' : 'إنشاء مرتجع بيع',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'فواتير المبيعات', 'url' => $this->routeContext->invoicesPath()],
                ['label' => $form['isEdit'] ? 'تعديل مرتجع بيع' : 'إنشاء مرتجع بيع'],
            ],
            'sales_invoice_view_base_url' => $this->routeContext->invoiceViewPath(),
            'sales_returns_url' => $this->routeContext->returnsPath(),
            'sales_return_view_url' => $returnId > 0 ? $this->routeContext->returnViewPath($returnId) : null,
        ]);
    }

    public function view(): void
    {
        Auth::requireLogin();
        if (!$this->ensureSchema()) return;
        $id = (int) Request::get('id', 0);
        if ($id <= 0) { http_response_code(400); exit('Invalid'); }

        if (Request::isPost()) {
            Csrf::verify();
            $action = (string) Request::post('action', '');
            try {
                if ($action === 'cancel') {
                    require_permission('sales_returns.cancel');
                    $this->service->cancelDraft($id);
                    Response::flash('success', 'تم إلغاء مرتجع البيع (مسودة).');
                    Response::redirect($this->routeContext->returnViewPath($id));
                    return;
                }
                if ($action === 'post') {
                    require_permission('sales_returns.post');
                    $this->service->post($id, current_user_id() ? (int) current_user_id() : 0);
                    Response::flash('success', 'تم ترحيل مرتجع البيع.');
                    Response::redirect($this->routeContext->returnViewPath($id));
                    return;
                }
            } catch (Throwable $e) {
                Response::flash('danger', (($action === 'post') ? 'تعذر ترحيل مرتجع البيع: ' : 'تعذر إلغاء مرتجع البيع: ') . $e->getMessage());
                Response::redirect($this->routeContext->returnViewPath($id));
                return;
            }
        }

        $return = $this->returns->findViewById($id);
        if (!$return) { http_response_code(404); exit('Not found'); }

        Response::view('pages/sales/return_view', [
            'return' => $return,
            'lines' => $this->returns->fetchReturnItems($id),
            'page_title' => 'عرض مرتجع بيع',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'مرتجعات البيع', 'url' => $this->routeContext->returnsPath()],
                ['label' => 'عرض'],
            ],
            'sales_invoice_view_base_url' => $this->routeContext->invoiceViewPath(),
            'sales_returns_url' => $this->routeContext->returnsPath(),
            'sales_return_form_url' => $this->routeContext->returnFormPath($id),
        ]);
    }
}
