<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Procurement\Models\ReturnToVendor;
use App\Modules\Procurement\Models\RtvItem;
use App\Modules\Procurement\Services\ReturnToVendorService;
use App\Modules\Inventory\Models\Supplier;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Models\InventoryItem;

class ReturnToVendorController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'status' => trim((string) $request->get('status', '')),
            'supplier_id' => trim((string) $request->get('supplier_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 = ReturnToVendor::search($filters, 25, $page);

        return $this->view('Procurement.Views.rtv.index', [
            'rtvs' => $result['data'], 'pagination' => $result['pagination'],
            'filters' => $filters, 'suppliers' => Supplier::allActive(),
            'statuses' => ReturnToVendor::getStatuses(),
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('Procurement.Views.rtv.form', [
            'suppliers' => Supplier::allActive(), 'warehouses' => Warehouse::allActive(),
            'items' => InventoryItem::allActive(),
        ]);
    }

    public function store(Request $request): Response
    {
        $header = [
            'supplier_id' => (int) $request->post('supplier_id', 0),
            'warehouse_id' => (int) $request->post('warehouse_id', 0),
            'grn_id' => (int) $request->post('grn_id', 0) ?: null,
            'reason' => trim((string) $request->post('reason', '')),
            'return_date' => trim((string) $request->post('return_date', '')) ?: date('Y-m-d'),
            'notes' => trim((string) $request->post('notes', '')) ?: null,
        ];

        $rawItems = $request->post('items', []);
        if (!is_array($rawItems) || empty($rawItems)) {
            return $this->redirect('/procurement/rtv/create')->withError('يجب إضافة صنف واحد على الأقل');
        }

        $items = [];
        foreach ($rawItems as $raw) {
            $qty = (string) ($raw['quantity'] ?? '0');
            if (bccomp($qty, '0', 3) > 0 && !empty($raw['item_id'])) {
                $items[] = [
                    'item_id' => (int) $raw['item_id'], 'quantity' => $qty,
                    'unit_cost' => $raw['unit_cost'] ?? '0', 'batch_number' => $raw['batch_number'] ?? null,
                    'reason' => $raw['reason'] ?? null,
                ];
            }
        }

        try {
            $rtvId = ReturnToVendorService::createRTV($header, $items);
            return $this->redirect('/procurement/rtv/' . $rtvId)->withSuccess('تم إنشاء مرتجع المورد بنجاح');
        } catch (\RuntimeException $e) {
            return $this->redirect('/procurement/rtv/create')->withError($e->getMessage());
        }
    }

    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $rtv = $db->selectOne(
            "SELECT r.*, s.`name_ar` as supplier_name, w.`name_ar` as warehouse_name, g.`grn_number`
             FROM `return_to_vendor` r
             JOIN `suppliers` s ON s.`id` = r.`supplier_id`
             JOIN `warehouses` w ON w.`id` = r.`warehouse_id`
             LEFT JOIN `goods_received_notes` g ON g.`id` = r.`grn_id`
             WHERE r.`id` = ?", [(int) $id]
        );
        if (!$rtv) return $this->redirect('/procurement/rtv')->withError('مرتجع المورد غير موجود');

        return $this->view('Procurement.Views.rtv.show', [
            'rtv' => $rtv, 'items' => RtvItem::getForRTV((int) $id),
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $rtv = $db->selectOne("SELECT * FROM `return_to_vendor` WHERE `id` = ?", [(int) $id]);
        if (!$rtv || $rtv['status'] !== 'draft') return $this->redirect('/procurement/rtv/' . $id)->withError('لا يمكن تعديل المرتجع');

        return $this->view('Procurement.Views.rtv.form', [
            'rtv' => $rtv, 'rtvItems' => RtvItem::getForRTV((int) $id),
            'suppliers' => Supplier::allActive(), 'warehouses' => Warehouse::allActive(),
            'items' => InventoryItem::allActive(),
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم تحديث المرتجع');
    }

    public function submit(Request $request, string $id): Response
    {
        try { ReturnToVendorService::submitRTV((int) $id); return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم تقديم المرتجع للاعتماد'); }
        catch (\RuntimeException $e) { return $this->redirect('/procurement/rtv/' . $id)->withError($e->getMessage()); }
    }

    public function approve(Request $request, string $id): Response
    {
        try { ReturnToVendorService::approveRTV((int) $id); return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم اعتماد المرتجع'); }
        catch (\RuntimeException $e) { return $this->redirect('/procurement/rtv/' . $id)->withError($e->getMessage()); }
    }

    public function ship(Request $request, string $id): Response
    {
        try { ReturnToVendorService::shipRTV((int) $id); return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم شحن المرتجع'); }
        catch (\RuntimeException $e) { return $this->redirect('/procurement/rtv/' . $id)->withError($e->getMessage()); }
    }

    public function complete(Request $request, string $id): Response
    {
        try { ReturnToVendorService::completeRTV((int) $id); return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم إتمام المرتجع — سيتم تسجيل القيد المحاسبي'); }
        catch (\RuntimeException $e) { return $this->redirect('/procurement/rtv/' . $id)->withError($e->getMessage()); }
    }

    public function cancel(Request $request, string $id): Response
    {
        try { ReturnToVendorService::cancelRTV((int) $id); return $this->redirect('/procurement/rtv/' . $id)->withSuccess('تم إلغاء المرتجع'); }
        catch (\RuntimeException $e) { return $this->redirect('/procurement/rtv/' . $id)->withError($e->getMessage()); }
    }
}
