<?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\PurchaseReturnRepository;
use App\Services\PurchaseReturnService;
use Throwable;
use App\Modules\Purchases\Application\Services\PurchasesRouteContext;

final class PurchaseReturnController
{
    private \PDO $pdo;
    private PurchaseReturnRepository $repo;
    private PurchaseReturnService $service;
    private PurchasesRouteContext $routeContext;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->repo = new PurchaseReturnRepository($this->pdo);
        $this->service = new PurchaseReturnService($this->pdo, $this->repo);
        $this->routeContext = new PurchasesRouteContext();
    }

    private function ensureSchemaView(): bool
    {
        try {
            $this->service->ensureSchemaOrThrow();
            return true;
        } catch (Throwable $e) {
            Response::view('pages/dashboard', ['error' => $e->getMessage()]);
            return false;
        }
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('purchase_returns.view');
        if (!$this->ensureSchemaView()) return;
        $q = trim((string)Request::get('q', ''));
        $status = trim((string)Request::get('status', ''));
        $from = trim((string)Request::get('from', ''));
        $to = trim((string)Request::get('to', ''));
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($this->repo->search($q, $status, $from, $to), $page, 25);
        Response::view('pages/purchases/returns_index', [
            'purchase_invoices_url' => $this->routeContext->invoicesPath(),
            'purchase_returns_url' => $this->routeContext->returnsPath(),
            'purchase_return_view_base_url' => $this->routeContext->returnViewPath(),
            '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'=>strtoupper($status),'from'=>$from,'to'=>$to,
            'page_title' => 'مرتجعات الشراء',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label'=>'المشتريات','url'=>$this->routeContext->purchasesBoardPath()],
                ['label'=>'مرتجعات الشراء'],
            ],
        ]);
    }

    public function form(): void
    {
        Auth::requireLogin();
        require_permission('purchase_returns.create');
        if (!$this->ensureSchemaView()) return;
        $returnId = (int)Request::get('id', 0);
        $invoiceId = (int)Request::get('invoice_id', 0);
        try {
            if (Request::isPost()) {
                Csrf::verify();
                $savedId = $this->service->saveDraft($returnId, $invoiceId, Request::all(), (int)(current_user_id() ?: 0));
                Response::flash('success', 'تم حفظ المرتجع كمسودة.');
                Response::redirect($this->routeContext->returnViewPath($savedId));
                return;
            }
            $data = $this->service->loadForm($returnId, $invoiceId);
            Response::view('pages/purchases/return_form', [
                'purchase_invoice_view_url' => $this->routeContext->invoiceViewPath((int)($data['invoice']['id'] ?? 0)),
                'purchase_return_view_url' => $this->routeContext->returnViewPath($returnId),
                'return' => $data['return'],
                'lines' => $data['lines'],
                'invoice' => $data['invoice'],
                'isEdit' => $data['isEdit'],
                'return_id' => $returnId,
                'page_title' => $returnId > 0 ? 'تعديل مرتجع شراء' : 'إنشاء مرتجع شراء',
                'breadcrumbs' => [
                    $this->routeContext->dashboardCrumb(),
                    ['label'=>'مرتجعات الشراء','url'=>$this->routeContext->returnsPath()],
                    ['label'=>$returnId > 0 ? 'تعديل' : 'إنشاء'],
                ],
            ]);
        } catch (Throwable $e) {
            $msg = $e->getMessage();
            if (in_array($msg, ['invoice_id required','Not found','Invoice not found'], true)) {
                http_response_code($msg === 'invoice_id required' ? 400 : 404);
                exit($msg);
            }
            Response::flash('danger', $msg);
            Response::redirect($returnId > 0 ? $this->routeContext->returnFormPath($returnId) : $this->routeContext->invoicesPath(true));
        }
    }

    public function view(): void
    {
        Auth::requireLogin();
        require_permission('purchase_returns.view');
        if (!$this->ensureSchemaView()) 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 === 'post') {
                    require_permission('purchase_returns.post');
                    $this->service->post($id, (int)(current_user_id() ?: 0));
                    Response::flash('success', 'تم ترحيل مرتجع الشراء.');
                } elseif ($action === 'cancel') {
                    require_permission('purchase_returns.create');
                    $this->service->cancelDraft($id);
                    Response::flash('success', 'تم إلغاء المرتجع (مسودة).');
                }
            } catch (Throwable $e) {
                Response::flash('danger', (($action === 'post') ? 'تعذر الترحيل: ' : 'تعذر الإلغاء: ') . $e->getMessage());
            }
            Response::redirect($this->routeContext->returnViewPath($id));
            return;
        }

        $return = $this->repo->findViewById($id);
        if (!$return) { http_response_code(404); exit('Not found'); }
        Response::view('pages/purchases/return_view', [
            'purchase_returns_url' => $this->routeContext->returnsPath(),
            'purchase_return_form_url' => $this->routeContext->returnFormPath(),
            'return' => $return,
            'lines' => $this->repo->fetchLines($id),
            'page_title' => 'عرض مرتجع شراء',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label'=>'مرتجعات الشراء','url'=>$this->routeContext->returnsPath()],
                ['label'=>'عرض'],
            ],
        ]);
    }
}
