<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Inventory\Models\StockTransfer;
use App\Modules\Inventory\Models\StockTransferItem;
use App\Modules\Inventory\Models\InventoryItem;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\StockTransferService;

class StockTransferController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'status'            => trim((string) $request->get('status', '')),
            'from_warehouse_id' => trim((string) $request->get('from_warehouse_id', '')),
            'to_warehouse_id'   => trim((string) $request->get('to_warehouse_id', '')),
            'date_from'         => trim((string) $request->get('date_from', '')),
            'date_to'           => trim((string) $request->get('date_to', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = StockTransfer::search($filters, 25, $page);

        return $this->view('Inventory.Views.stock.transfers', [
            'transfers'  => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'warehouses' => Warehouse::allActive(),
            'statuses'   => StockTransfer::getStatuses(),
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('Inventory.Views.stock.transfer_form', [
            'warehouses' => Warehouse::allActive(),
            'items'      => InventoryItem::allActive(),
        ]);
    }

    public function store(Request $request): Response
    {
        $fromWarehouse = (int) $request->post('from_warehouse_id', 0);
        $toWarehouse   = (int) $request->post('to_warehouse_id', 0);
        $transferDate  = trim((string) $request->post('transfer_date', date('Y-m-d')));
        $notes         = trim((string) $request->post('notes', ''));

        $itemIds    = $request->post('item_ids', []);
        $quantities = $request->post('quantities', []);

        if (!is_array($itemIds) || empty($itemIds)) {
            return $this->redirect('/inventory/transfers/create')->withError('يجب إضافة صنف واحد على الأقل');
        }

        $items = [];
        foreach ($itemIds as $i => $itemId) {
            $qty = $quantities[$i] ?? '0';
            if ((int) $itemId > 0 && bccomp((string) $qty, '0', 3) > 0) {
                $items[] = [
                    'item_id'  => (int) $itemId,
                    'quantity' => (string) $qty,
                ];
            }
        }

        try {
            $transferId = StockTransferService::createTransfer([
                'from_warehouse_id' => $fromWarehouse,
                'to_warehouse_id'   => $toWarehouse,
                'transfer_date'     => $transferDate,
                'notes'             => $notes,
            ], $items);

            return $this->redirect('/inventory/transfers/' . $transferId)->withSuccess('تم إنشاء طلب التحويل بنجاح');
        } catch (\RuntimeException $e) {
            return $this->redirect('/inventory/transfers/create')->withError($e->getMessage());
        }
    }

    public function show(Request $request, string $id): Response
    {
        $transfer = StockTransfer::find((int) $id);
        if (!$transfer) {
            return $this->redirect('/inventory/transfers')->withError('التحويل غير موجود');
        }

        $items = StockTransferItem::getForTransfer((int) $id);

        $db = App::getInstance()->db();
        $fromWarehouse = $db->selectOne("SELECT `name_ar`, `code` FROM `warehouses` WHERE `id` = ?", [(int) $transfer->from_warehouse_id]);
        $toWarehouse = $db->selectOne("SELECT `name_ar`, `code` FROM `warehouses` WHERE `id` = ?", [(int) $transfer->to_warehouse_id]);

        return $this->view('Inventory.Views.stock.transfer_show', [
            'transfer'      => $transfer,
            'items'         => $items,
            'fromWarehouse' => $fromWarehouse,
            'toWarehouse'   => $toWarehouse,
            'statuses'      => StockTransfer::getStatuses(),
        ]);
    }

    public function approve(Request $request, string $id): Response
    {
        try {
            StockTransferService::approve((int) $id);
            return $this->redirect('/inventory/transfers/' . $id)->withSuccess('تمت الموافقة على التحويل');
        } catch (\RuntimeException $e) {
            return $this->redirect('/inventory/transfers/' . $id)->withError($e->getMessage());
        }
    }

    public function receive(Request $request, string $id): Response
    {
        try {
            StockTransferService::receive((int) $id);
            return $this->redirect('/inventory/transfers/' . $id)->withSuccess('تم استلام التحويل وتحديث الأرصدة بنجاح');
        } catch (\RuntimeException $e) {
            return $this->redirect('/inventory/transfers/' . $id)->withError($e->getMessage());
        }
    }
}
