<?php

declare(strict_types=1);

namespace App\Modules\Inventory\Application\Services;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Repositories\OpeningStockRepository;
use App\Services\OpeningStockService;
use App\Shared\Support\RoutePaths;
use PDO;
use Throwable;

final class OpeningStockPageService
{
    private PDO $pdo;
    private OpeningStockRepository $repo;
    private OpeningStockService $service;

    public function __construct(?PDO $pdo = null)
    {
        $this->pdo = $pdo ?? DB::pdo();
        $this->repo = new OpeningStockRepository($this->pdo);
        $this->service = new OpeningStockService($this->pdo, $this->repo);
    }

    public function handle(): void
    {
        Auth::requireLogin();
        $action = (string) Request::input('action', '');
        $id = Request::int('id');

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $this->handlePost((string) Request::post('action', ''), $id);
                return;
            }

            if ($action === 'edit' && $id > 0) {
                $doc = $this->repo->findDoc($id);
                if (!$doc) {
                    Response::flash('danger', 'المستند غير موجود');
                    Response::redirect(RoutePaths::openingStockBase());
                    return;
                }

                $this->renderEdit($doc, $id);
                return;
            }

            $this->renderIndex();
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect($id > 0 ? (RoutePaths::openingStockBase() . '?action=edit&id=' . $id) : RoutePaths::openingStockBase());
        }
    }

    public function renderIndex(): void
    {
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($this->repo->listDocs(), $page, 25);
        Response::view('pages/warehouse/opening_list', [
            'docs' => $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'],
            'warehouses' => $this->repo->activeWarehouses(),
            'page_title' => 'افتتاحيات المخزون',
            'breadcrumbs' => $this->breadcrumbs(),
        ]);
    }

    public function renderEdit(array $doc, int $id): void
    {
        Response::view('pages/warehouse/opening_edit', [
            'doc' => $doc,
            'lines' => $this->repo->linesForDoc($id),
            'warehouses' => $this->repo->activeWarehouses(),
            'items' => $this->repo->activeItems(),
            'units' => $this->repo->allUnits(),
            'page_title' => 'افتتاحيات المخزون',
            'breadcrumbs' => $this->breadcrumbs(),
        ]);
    }

    private function handlePost(string $action, int $id): void
    {
        if ($action === 'create') {
            $newId = $this->service->create(Request::all());
            Response::flash('success', 'تم إنشاء مستند افتتاحي');
            Response::redirect(RoutePaths::openingStockBase() . '?action=edit&id=' . $newId);
            return;
        }
        if ($action === 'add_line') {
            $docId = Request::int('doc_id');
            $this->service->addLine(Request::all());
            Response::flash('success', 'تم إضافة السطر');
            Response::redirect(RoutePaths::openingStockBase() . '?action=edit&id=' . $docId);
            return;
        }
        if ($action === 'update_line') {
            $docId = Request::int('doc_id');
            $this->service->updateLine(Request::all());
            Response::flash('success', 'تم حفظ السطر');
            Response::redirect(RoutePaths::openingStockBase() . '?action=edit&id=' . $docId);
            return;
        }
        if ($action === 'delete') {
            $docId = Request::int('doc_id');
            $this->service->deleteDoc($docId);
            Response::flash('success', 'تم حذف المستند');
            Response::redirect(RoutePaths::openingStockBase());
            return;
        }
        if ($action === 'delete_line') {
            $docId = Request::int('doc_id');
            $this->service->deleteLine($docId, Request::int('line_id'));
            Response::flash('success', 'تم الحذف');
            Response::redirect(RoutePaths::openingStockBase() . '?action=edit&id=' . $docId);
            return;
        }
        if ($action === 'post') {
            $docId = Request::int('doc_id');
            $this->service->post($docId);
            Response::flash('success', 'تم ترحيل الافتتاحي');
            Response::redirect(RoutePaths::openingStockBase() . '?action=edit&id=' . $docId);
            return;
        }

        Response::flash('warning', 'الإجراء غير معروف');
        Response::redirect($id > 0 ? (RoutePaths::openingStockBase() . '?action=edit&id=' . $id) : RoutePaths::openingStockBase());
    }



    public function print(): void
    {
        Auth::requireLogin();
        $id = Request::int('id');
        $format = strtolower((string) Request::get('format', ''));
        if ($id <= 0) {
            http_response_code(400);
            exit('Invalid document id');
        }
        if ($format === '') {
            print_format_chooser(
                RoutePaths::openingStockBase() . '/print?id=' . $id . '&format=a4',
                RoutePaths::openingStockBase() . '/print?id=' . $id . '&format=receipt',
                'طباعة افتتاحي مخزون'
            );
            return;
        }
        if (!in_array($format, ['a4', 'receipt'], true)) {
            $format = 'a4';
        }

        $doc = $this->repo->findDoc($id);
        if (!$doc) {
            http_response_code(404);
            exit('Document not found');
        }
        $lines = $this->repo->linesForDoc($id);
        print_view($format, 'opening_doc', [
            'title' => 'افتتاحي مخزون',
            'meta' => [
                'no' => (string)($doc['doc_no'] ?? ''),
                'date' => (string)substr((string)($doc['doc_date'] ?? ''), 0, 10),
                'status' => (string)($doc['status'] ?? ''),
            ],
            'company' => company_profile($this->pdo),
            'footer' => [],
            'print_format' => $format,
            'doc' => $doc,
            'lines' => $lines,
            'warehouse_name' => (string)($doc['warehouse_name'] ?? '-'),
            'notes' => (string)($doc['notes'] ?? '-'),
        ]);
    }

    private function breadcrumbs(): array
    {
        return [
            ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
            ['label' => 'افتتاحيات المخزون', 'url' => RoutePaths::openingStockBase()],
        ];
    }
}
