<?php
declare(strict_types=1);

// Rest of your code...
namespace Controllers;
use Helpers\Auth; use Helpers\Request; use Helpers\Response; use Repositories\OrderRepository; use Config\Database;
final class AdminOrderController
{
    private function admin(): array { $u=Auth::requireUser(); if(!Auth::isAdmin($u)) throw new \RuntimeException('Admin access required'); return $u; }
    public function index(): never { try{$this->admin(); Response::success((new OrderRepository())->adminList(Request::query()));}catch(\Throwable $e){Response::error($e->getMessage(), str_contains($e->getMessage(),'Admin')||str_contains($e->getMessage(),'Auth')?401:500);} }
    public function show(string $id): never { try{$this->admin(); $o=(new OrderRepository())->detailById((int)$id); if(!$o) Response::error('Order not found',404); Response::success($o);}catch(\Throwable $e){Response::error($e->getMessage(),str_contains($e->getMessage(),'Admin')||str_contains($e->getMessage(),'Auth')?401:500);} }
    public function updateStatus(string $id): never { try{$this->admin();$d=Request::input();if(empty($d['order_status'])) Response::error('order_status is required',422);(new OrderRepository())->updateStatus((int)$id,(string)$d['order_status']); Response::success([], 'Order status updated');}catch(\Throwable $e){Response::error($e->getMessage(),400);} }
    public function updateTracking(string $id): never {
        try {
            $this->admin();
            $d = Request::input();
            $db = Database::connection();
            $fields = []; $params = ['id' => (int)$id];
            if (isset($d['tracking_number'])) { $fields[] = 'tracking_number=:tracking_number'; $params['tracking_number'] = $d['tracking_number']; }
            if (isset($d['courier_partner'])) { $fields[] = 'courier_partner=:courier_partner'; $params['courier_partner'] = $d['courier_partner']; }
            if (isset($d['shipment_status'])) { $fields[] = 'shipment_status=:shipment_status'; $params['shipment_status'] = $d['shipment_status']; }
            if (empty($fields)) Response::error('No tracking fields provided', 422);
            $stmt = $db->prepare('UPDATE orders SET ' . implode(',', $fields) . ' WHERE id=:id');
            $stmt->execute($params);
            Response::success([], 'Tracking updated');
        } catch (\Throwable $e) { Response::error($e->getMessage(), 400); }
    }
}
