<?php

class KitchenIssueController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('stock', 'view');

        $issueModel = new KitchenIssue();
        $materialModel = new RawMaterial();
        $db = Database::getConnection();

        // Recipe data for recipe-tracked menu items — used to live-calculate estimated
        // packet output as materials are added to the New Kitchen Issue cart.
        $recipeRows = $db->query(
            "SELECT mi.item_name, r.raw_material_id, r.quantity_required, rm.material_name, rm.unit
             FROM recipes r
             JOIN menu_items mi ON mi.id = r.menu_item_id
             JOIN raw_materials rm ON rm.id = r.raw_material_id
             WHERE mi.track_stock = 1"
        )->fetchAll();
        $recipesByItem = [];
        foreach ($recipeRows as $row) {
            $recipesByItem[$row['item_name']][] = [
                'raw_material_id'   => (int) $row['raw_material_id'],
                'material_name'     => $row['material_name'],
                'unit'              => $row['unit'],
                'quantity_required' => (float) $row['quantity_required'],
            ];
        }

        $this->view('kitchen.index', [
            'pageTitle'   => 'Daily Kitchen Issuance',
            'issues'      => $issueModel->listRecent(30),
            'materials'   => $materialModel->allOrdered(),
            'stats'       => $issueModel->stats(),
            'lastIssue'   => $issueModel->mostRecentWithItems(),
            'recipesByItem' => $recipesByItem,
            'csrf'        => $this->csrfField(),
        ]);
    }

    public function store(): void
    {
        Auth::requirePermission('stock', 'edit');
        $this->verifyCsrf();

        $notes = trim($this->input('notes', ''));
        $cartJson = $this->input('cart_json', '[]');
        $cart = json_decode($cartJson, true);

        if (!is_array($cart) || count($cart) === 0) {
            $this->redirect('kitchen-issue');
            return;
        }

        $items = [];
        foreach ($cart as $line) {
            $materialId = (int) ($line['raw_material_id'] ?? 0);
            $qty = (float) ($line['quantity'] ?? 0);
            if ($materialId > 0 && $qty > 0) {
                $items[] = ['raw_material_id' => $materialId, 'quantity' => $qty];
            }
        }
        if (count($items) === 0) {
            $this->redirect('kitchen-issue');
            return;
        }

        $issueModel = new KitchenIssue();
        $issueId = $issueModel->createWithItems($notes, $items, Auth::id());

        AuditLogger::log(Auth::id(), 'KITCHEN_ISSUE_CREATE', 'stock', "Issued stock to kitchen — issue #{$issueId}");
        $this->redirect('kitchen-issue');
    }

    public function update(): void
    {
        Auth::requirePermission('stock', 'edit');
        $this->verifyCsrf();

        $issueId = (int) $this->input('id');
        $notes = trim($this->input('notes', ''));
        $cartJson = $this->input('cart_json', '[]');
        $cart = json_decode($cartJson, true);

        if ($issueId <= 0 || !is_array($cart) || count($cart) === 0) {
            $this->redirect('kitchen-issue');
            return;
        }

        $items = [];
        foreach ($cart as $line) {
            $materialId = (int) ($line['raw_material_id'] ?? 0);
            $qty = (float) ($line['quantity'] ?? 0);
            if ($materialId > 0 && $qty > 0) {
                $items[] = ['raw_material_id' => $materialId, 'quantity' => $qty];
            }
        }
        if (count($items) === 0) {
            $this->redirect('kitchen-issue');
            return;
        }

        $issueModel = new KitchenIssue();
        $issueModel->updateWithItems($issueId, $notes, $items, Auth::id());

        AuditLogger::log(Auth::id(), 'KITCHEN_ISSUE_UPDATE', 'stock', "Edited kitchen issue #{$issueId}");
        $this->redirect('kitchen-issue');
    }
}
