<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\OrderItemModel;
use App\Models\OrderModel;

class Order extends BaseController
{
    protected OrderModel $order;
    protected OrderItemModel $items;

    public function __construct()
    {
        helper(['url', 'form']);
        $this->order = new OrderModel();
        $this->items = new OrderItemModel();
    }

    public function index()
    {
        return view('owner/order/index', ['title' => 'Order', 'orders' => $this->order->orderBy('created_at', 'DESC')->findAll()]);
    }

    public function detail($id)
    {
        $order = $this->order->find($id);
        if (! $order) return redirect()->to('/owner/order')->with('error', 'Order tidak ditemukan.');
        return view('owner/order/detail', ['title' => 'Detail Order', 'order' => $order, 'items' => $this->items->getItems($id)]);
    }

    public function waiting($id) { return $this->setProduction($id, 'antrian', 'Order masuk antrian produksi.'); }
    public function process($id) { return $this->setProduction($id, 'produksi', 'Order sedang diproduksi.'); }
    public function finish($id) { return $this->setProduction($id, 'completed', 'Produksi selesai.'); }
    public function cancel($id) { return $this->setProduction($id, 'cancelled', 'Order dibatalkan.'); }
    public function history() { return $this->index(); }
    public function priority() { return $this->index(); }
    public function deadline() { return $this->index(); }

    private function setProduction(int $id, string $status, string $message)
    {
        $order = $this->order->find($id);
        if (! $order) return redirect()->back()->with('error', 'Order tidak ditemukan.');

        $normalizedStatus = $this->order->normalizeProductionStatus($status);
        $orderStatus = $normalizedStatus === 'completed' ? 'completed' : ($normalizedStatus === 'cancelled' ? 'cancelled' : 'production');

        $this->order->update($id, ['production_status' => $normalizedStatus, 'order_status' => $orderStatus]);
        return redirect()->back()->with('success', $message);
    }
}
