<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Modules\Bms\Entities\BmsTransferRequest;
use Yajra\DataTables\Facades\DataTables;

/**
 * P1 transfer oversight (read-only). Managers see the global transfer queue
 * with status and the acceptance audit; the request/accept actions live in
 * the employee PWA (P2).
 */
class TransferController extends BmsBaseController
{
    protected function statusLabels(): array
    {
        return [
            'requested'  => ['badge' => 'warning', 'label' => __('bms::lang.tr_requested')],
            'in_transit' => ['badge' => 'info', 'label' => __('bms::lang.tr_in_transit')],
            'accepted'   => ['badge' => 'success', 'label' => __('bms::lang.tr_accepted')],
            'rejected'   => ['badge' => 'danger', 'label' => __('bms::lang.tr_rejected')],
            'cancelled'  => ['badge' => 'default', 'label' => __('bms::lang.tr_cancelled')],
        ];
    }

    public function index()
    {
        $this->guard('bms.bookings.view');

        if (request()->ajax()) {
            $labels = $this->statusLabels();
            $types = ['warehouse_to_hall' => __('bms::lang.tr_wh_to_hall'), 'hall_to_hall' => __('bms::lang.tr_hall_to_hall')];

            $rows = BmsTransferRequest::where('bms_transfer_requests.business_id', $this->businessId())
                ->leftJoin('bms_halls', 'bms_halls.id', '=', 'bms_transfer_requests.to_hall_id')
                ->leftJoin('users', 'users.id', '=', 'bms_transfer_requests.accepted_by')
                ->withCount('items')
                ->select([
                    'bms_transfer_requests.id', 'bms_transfer_requests.type', 'bms_transfer_requests.status',
                    'bms_transfer_requests.accepted_at', 'bms_halls.name as to_hall',
                    DB::raw("CONCAT(COALESCE(users.first_name,''),' ',COALESCE(users.surname,'')) as acceptor"),
                ]);

            return DataTables::of($rows)
                ->editColumn('type', fn ($r) => $types[$r->type] ?? $r->type)
                ->editColumn('to_hall', fn ($r) => $r->to_hall ?? '—')
                ->addColumn('items_count', fn ($r) => $r->items_count)
                ->editColumn('status', function ($r) use ($labels) {
                    $s = $labels[$r->status] ?? ['badge' => 'default', 'label' => $r->status];
                    return '<span class="label label-'.$s['badge'].'">'.$s['label'].'</span>';
                })
                ->addColumn('acceptance', function ($r) {
                    if ($r->status !== 'accepted') {
                        return '—';
                    }
                    return trim($r->acceptor) . '<br><small class="text-muted">' . optional($r->accepted_at)->format('d M Y H:i') . '</small>';
                })
                ->rawColumns(['status', 'acceptance'])
                ->make(true);
        }

        return view('bms::transfers.index');
    }
}
