<?php
namespace App\Controllers\Admin;

use App\Models\Order;
use App\Models\Payment;
use Core\Payment\OrderService;

/** 后台：订单与付款管理（超级管理员 + 管理员） */
class OrderController extends AdminController
{
    public function index()
    {
        $order = new Order();
        $all = array_reverse($order->all()); // 最新在前
        return $this->view('admin/orders', ['orders' => $all, 'seg' => 'orders']);
    }

    public function show($id)
    {
        $order = new Order();
        $o = $order->find($id);
        if (!$o) { \Core\App::notFound(); return; }
        $payments = (new Payment())->whereAll('order_no', $o['order_no']);
        return $this->view('admin/order_show', ['o' => $o, 'payments' => $payments, 'seg' => 'orders']);
    }

    public function markPaid($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
            $order = new Order();
            $o = $order->find($id);
            if ($o && $o['status'] !== 'paid') {
                OrderService::markPaid($o['order_no'], 'MANUAL' . time(), $o['channel'] ?: 'manual');
            }
        }
        $this->redirect('admin/orders/show/' . $id);
    }

    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
            (new Order())->delete($id);
        }
        $this->redirect('admin/orders');
    }
}
