<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsArea;
use Modules\Bms\Entities\BmsVenue;
use Yajra\DataTables\Facades\DataTables;

class VenueController extends BmsBaseController
{
    public function index()
    {
        $this->guard('bms.venues.view');

        if (request()->ajax()) {
            $locations = $this->locations();

            $venues = BmsVenue::where('bms_venues.business_id', $this->businessId())
                ->leftJoin('bms_areas', 'bms_areas.id', '=', 'bms_venues.area_id')
                ->select([
                    'bms_venues.id', 'bms_venues.name', 'bms_venues.name_ar',
                    'bms_venues.location_id', 'bms_venues.city', 'bms_venues.is_active',
                    'bms_areas.name as area_name',
                ])
                ->withCount('halls'); // after select() so the count subquery is retained

            return DataTables::of($venues)
                ->editColumn('location_id', fn ($v) => $locations[$v->location_id] ?? '—')
                ->editColumn('area_name', fn ($v) => $v->area_name ?? '—')
                ->addColumn('halls_count', fn ($v) => $v->halls_count)
                ->editColumn('is_active', fn ($v) => $v->is_active
                    ? '<span class="label label-success">'.__('bms::lang.active').'</span>'
                    : '<span class="label label-default">'.__('bms::lang.inactive').'</span>')
                ->addColumn('action', function ($v) {
                    $edit = '<button data-href="'.route('bms.venues.edit', $v->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary bms-modal-btn"><i class="glyphicon glyphicon-edit"></i> '.__('messages.edit').'</button>';
                    $del = '<button data-href="'.route('bms.venues.destroy', $v->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-error bms-delete"><i class="glyphicon glyphicon-trash"></i> '.__('messages.delete').'</button>';
                    return $edit.' '.$del;
                })
                ->rawColumns(['action', 'is_active'])
                ->make(true);
        }

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

    public function create()
    {
        $this->guard('bms.venues.manage');
        return view('bms::venues.create', [
            'locations' => $this->locations(),
            'areas'     => $this->areaOptions(),
        ]);
    }

    public function store(Request $request)
    {
        $this->guard('bms.venues.manage');
        $data = $this->validatedData($request);

        try {
            $data['business_id'] = $this->businessId();
            $data['is_active'] = $request->boolean('is_active');
            $data['working_hours'] = $this->workingHours($request);
            BmsVenue::create($data);
            BmsArea::syncFromLocations($this->businessId());
            return $this->ok(__('bms::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function edit($id)
    {
        $this->guard('bms.venues.manage');
        $venue = BmsVenue::where('business_id', $this->businessId())->findOrFail($id);
        return view('bms::venues.edit', [
            'venue'     => $venue,
            'locations' => $this->locations(),
            'areas'     => $this->areaOptions(),
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->guard('bms.venues.manage');
        $data = $this->validatedData($request);

        try {
            $venue = BmsVenue::where('business_id', $this->businessId())->findOrFail($id);
            $data['is_active'] = $request->boolean('is_active');
            $data['working_hours'] = $this->workingHours($request);
            $venue->update($data);
            BmsArea::syncFromLocations($this->businessId());
            return $this->ok(__('bms::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('bms.venues.manage');
        try {
            BmsVenue::where('business_id', $this->businessId())->findOrFail($id)->delete();
            BmsArea::syncFromLocations($this->businessId());
            return $this->ok(__('bms::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    protected function validatedData(Request $request): array
    {
        return $this->validate($request, [
            'name'        => 'required|string|max:191',
            'name_ar'     => 'nullable|string|max:191',
            'code'        => 'nullable|string|max:60',
            'location_id' => 'nullable|integer',
            'area_id'     => 'nullable|integer',
            'address'     => 'nullable|string',
            'city'        => 'nullable|string|max:100',
            'phone'       => 'nullable|string|max:30',
            'description' => 'nullable|string',
            'is_active'   => 'nullable',
        ]);
    }

    /** Build the working-hours config from the form (use-default toggle / days / open / close). */
    protected function workingHours(Request $request): array
    {
        if ($request->input('wh_mode', 'default') !== 'custom') {
            return ['use_default' => true];
        }
        return [
            'use_default' => false,
            'days'        => array_values(array_map('intval', (array) $request->input('wh_days', []))),
            'open'        => $request->input('wh_open', '10:00'),
            'close'       => $request->input('wh_close', '22:00'),
        ];
    }

    protected function areaOptions(): array
    {
        return BmsArea::where('business_id', $this->businessId())
            ->orderBy('name')->pluck('name', 'id')->toArray();
    }
}
