<?php

namespace Modules\Bms\Http\Controllers;

use Modules\Bms\Entities\BmsBooking;
use Modules\Bms\Entities\BmsDocument;
use Modules\Bms\Entities\BmsHall;
use Modules\Bms\Services\Contracts\InvoiceServiceContract;
use Modules\Bms\Services\Contracts\PaymentServiceContract;
use Yajra\DataTables\Facades\DataTables;

/**
 * Contracts area — the lifecycle of a banquet agreement:
 *   Initial request (lead/tentative) → Final contract (signed) → Invoice & payment.
 * Centred on the booking; surfaces the contract document, the default-script ERP
 * invoice + payment tracking, and the generated task set so it's findable in one
 * place (the booking ops console handles the operational edits).
 */
class ContractController extends BmsBaseController
{
    public function index()
    {
        $this->guard('bms.bookings.view');

        if (request()->ajax()) {
            $rows = BmsBooking::where('bms_bookings.business_id', $this->businessId())
                ->leftJoin('contacts', 'contacts.id', '=', 'bms_bookings.contact_id')
                ->select(['bms_bookings.id', 'bms_bookings.booking_no', 'bms_bookings.status', 'bms_bookings.event_date',
                    'bms_bookings.total_amount', 'bms_bookings.contracted_at', 'contacts.name as contact_name']);

            return DataTables::of($rows)
                ->editColumn('contact_name', fn ($b) => $b->contact_name ?: '—')
                ->editColumn('event_date', fn ($b) => $b->event_date ? \Carbon\Carbon::parse($b->event_date)->format('Y-m-d') : '—')
                ->addColumn('stage', fn ($b) => $this->stageBadge($b->status))
                ->editColumn('total_amount', fn ($b) => '<span class="display_currency" data-currency_symbol="true">'.$b->total_amount.'</span>')
                ->addColumn('action', fn ($b) => '<a href="'.route('bms.contracts.show', $b->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary"><i class="fa fa-file-contract"></i> '.__('messages.view').'</a>')
                ->rawColumns(['stage', 'total_amount', 'action'])
                ->make(true);
        }

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

    public function show($id)
    {
        $this->guard('bms.bookings.view');
        $booking = BmsBooking::with(['contact:id,name,mobile,email', 'halls'])
            ->where('business_id', $this->businessId())->findOrFail($id);

        return view('bms::contracts.show', [
            'booking'   => $booking,
            'invoice'   => app(InvoiceServiceContract::class)->statusForBooking($booking),
            'payments'  => app(PaymentServiceContract::class)->scheduleForBooking($this->businessId(), $booking->id)['payments'] ?? [],
            'tasks'     => \Modules\Bms\Entities\BmsTask::where('booking_id', $booking->id)->orderBy('due_at')->get(),
            'documents' => BmsDocument::where('booking_id', $booking->id)->latest()->get(),
            'proposals' => $booking->lead_id ? BmsDocument::where('lead_id', $booking->lead_id)->where('type', 'proposal')->latest()->get() : collect(),
            'hallNames' => BmsHall::whereIn('id', $booking->halls->pluck('hall_id'))->pluck('name', 'id'),
            'canManage' => auth()->user()->can('bms.bookings.manage'),
        ]);
    }

    /** A coarse lifecycle stage for the contract list. */
    protected function stageBadge(string $status): string
    {
        $map = [
            'tentative' => ['request', 'label-warning'], 'confirmed' => ['contract', 'label-primary'],
            'contracted' => ['contract', 'label-info'], 'completed' => ['completed', 'label-success'],
            'cancelled' => ['cancelled', 'label-default'],
        ];
        [$key, $class] = $map[$status] ?? ['request', 'label-default'];
        return '<span class="label '.$class.'">'.__('bms::lang.cstage_'.$key).'</span>';
    }
}
