<?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\Services\BomService;

class BomController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('inventory.bom.view');
        $db = App::getInstance()->db();

        $boms = $db->select(
            "SELECT b.*, i.name_ar as item_name, i.sku,
                    (SELECT COUNT(*) FROM bom_components WHERE bom_id = b.id) as component_count
             FROM bill_of_materials b
             JOIN inventory_items i ON i.id = b.item_id
             WHERE b.is_active = 1
             ORDER BY b.created_at DESC"
        );

        return $this->view('Inventory.Views.bom.index', ['boms' => $boms]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('inventory.bom.manage');
        $db = App::getInstance()->db();

        $items = $db->select("SELECT id, name_ar, sku FROM inventory_items WHERE is_archived = 0 ORDER BY name_ar");

        return $this->view('Inventory.Views.bom.form', [
            'bom' => null,
            'items' => $items,
            'components' => [],
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('inventory.bom.manage');

        $data = [
            'item_id' => (int) $request->post('item_id'),
            'name_ar' => $request->post('name_ar'),
            'name_en' => $request->post('name_en'),
            'output_quantity' => $request->post('output_quantity', '1'),
            'notes' => $request->post('notes'),
        ];

        $componentItemIds = $request->post('component_item_ids', []);
        $componentQtys = $request->post('component_quantities', []);
        $componentUnits = $request->post('component_units', []);
        $componentWaste = $request->post('component_waste', []);

        $components = [];
        for ($i = 0; $i < count($componentItemIds); $i++) {
            if (empty($componentItemIds[$i])) continue;
            $components[] = [
                'item_id' => (int) $componentItemIds[$i],
                'quantity' => $componentQtys[$i] ?? '1',
                'unit' => $componentUnits[$i] ?? null,
                'waste_percentage' => $componentWaste[$i] ?? '0',
            ];
        }

        if (empty($components)) {
            return $this->redirect('/inventory/bom/create')->withError('يجب إضافة مكون واحد على الأقل');
        }

        $result = BomService::create($data, $components);

        if (!$result['success']) {
            return $this->redirect('/inventory/bom/create')->withError($result['error']);
        }

        return $this->redirect('/inventory/bom/' . $result['bom_id'])->withSuccess('تم إنشاء قائمة المواد بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('inventory.bom.view');
        $db = App::getInstance()->db();

        $bom = $db->selectOne(
            "SELECT b.*, i.name_ar as item_name, i.sku
             FROM bill_of_materials b
             JOIN inventory_items i ON i.id = b.item_id
             WHERE b.id = ?",
            [(int) $id]
        );

        if (!$bom) {
            return $this->redirect('/inventory/bom')->withError('قائمة المواد غير موجودة');
        }

        $components = $db->select(
            "SELECT bc.*, i.name_ar as component_name, i.sku as component_sku
             FROM bom_components bc
             JOIN inventory_items i ON i.id = bc.component_item_id
             WHERE bc.bom_id = ?
             ORDER BY bc.sort_order",
            [(int) $id]
        );

        $costData = BomService::calculateCost((int) $id);

        return $this->view('Inventory.Views.bom.show', [
            'bom' => $bom,
            'components' => $components,
            'costData' => $costData,
        ]);
    }
}
