<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsAddon;
use Modules\Bms\Entities\BmsProductMeta;
use Yajra\DataTables\Facades\DataTables;

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

        if (request()->ajax()) {
            $addons = BmsAddon::where('business_id', $this->businessId())
                ->select(['id', 'name', 'name_ar', 'category', 'price', 'unit', 'is_active']);

            return DataTables::of($addons)
                ->editColumn('category', fn ($a) => $a->category ? ucwords($a->category) : '—')
                ->editColumn('price', fn ($a) => '<span class="display_currency" data-currency_symbol="true">'.$a->price.'</span>')
                ->editColumn('is_active', fn ($a) => $a->is_active
                    ? '<span class="label label-success">'.__('bms::lang.active').'</span>'
                    : '<span class="label label-default">'.__('bms::lang.inactive').'</span>')
                ->addColumn('action', function ($a) {
                    $edit = '<button data-href="'.route('bms.addons.edit', $a->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.addons.destroy', $a->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', 'price'])
                ->make(true);
        }

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

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

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

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

    public function edit($id)
    {
        $this->guard('bms.addons.manage');
        $addon = BmsAddon::where('business_id', $this->businessId())->findOrFail($id);
        return view('bms::addons.edit', ['addon' => $addon, 'addonProducts' => $this->addonProducts()]);
    }

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

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

    /** Add-on-flagged products (id => name) for the picker. */
    protected function addonProducts(): array
    {
        return \App\Product::where('products.business_id', $this->businessId())
            ->join('bms_product_meta', 'bms_product_meta.product_id', '=', 'products.id')
            ->where('bms_product_meta.is_addon', true)
            ->orderBy('products.name')
            ->pluck('products.name', 'products.id')->toArray();
    }

    /** Fill blank name/price/unit from the linked product (single source of truth). */
    protected function inheritFromProduct(array $data): array
    {
        $pid = (int) ($data['product_id'] ?? 0);
        if ($pid <= 0) {
            return $data;
        }
        $product = \App\Product::where('business_id', $this->businessId())->find($pid);
        $meta = BmsProductMeta::where('product_id', $pid)->first();
        if ($product) {
            $data['name'] = $data['name'] ?: $product->name;
            $data['name_ar'] = $data['name_ar'] ?: ($meta->name_ar ?? null);
        }
        if (empty($data['price']) && $meta && $meta->addon_price !== null) {
            $data['price'] = (float) $meta->addon_price;
        }
        $data['unit'] = $data['unit'] ?: ($meta->addon_unit ?? null);
        $data['price'] = $data['price'] ?? 0;

        return $data;
    }

    public function destroy($id)
    {
        $this->guard('bms.addons.manage');
        try {
            BmsAddon::where('business_id', $this->businessId())->findOrFail($id)->delete();
            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, [
            'product_id'  => 'required|integer',
            'name'        => 'nullable|string|max:191', // inherits from the product when blank
            'name_ar'     => 'nullable|string|max:191',
            'category'    => 'nullable|string|max:60',
            'price'       => 'nullable|numeric|min:0',   // inherits the product's add-on price when blank
            'unit'        => 'nullable|string|max:30',
            'description' => 'nullable|string',
            'is_active'   => 'nullable',
        ]);
    }
}
