<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcPortalOwner;
use Yajra\DataTables\Facades\DataTables;

/**
 * Phase 3 — back-office administration of vehicle-owner portal accounts. Staff
 * create/enable accounts here; owners then sign in via the public phone-OTP portal.
 */
class PortalAccountController extends VrcBaseController
{
    public function index()
    {
        $this->guard('vrc.portal.manage');

        if (request()->ajax()) {
            $q = VrcPortalOwner::where('business_id', $this->businessId())
                ->select(['id', 'name', 'phone', 'email', 'is_active', 'last_login_at']);

            return DataTables::of($q)
                ->editColumn('is_active', fn ($o) => $o->is_active
                    ? '<span class="label label-success">Active</span>'
                    : '<span class="label label-default">Disabled</span>')
                ->editColumn('last_login_at', fn ($o) => $o->last_login_at ? $o->last_login_at->format('d M Y H:i') : '—')
                ->addColumn('action', function ($o) {
                    $label = $o->is_active ? 'Disable' : 'Enable';
                    $cls = $o->is_active ? 'btn-warning' : 'btn-success';
                    return '<form method="POST" action="' . route('vrc.portal-accounts.toggle', $o->id) . '" style="display:inline">'
                        . csrf_field()
                        . '<button class="btn btn-xs ' . $cls . '">' . $label . '</button></form>';
                })
                ->rawColumns(['is_active', 'action'])
                ->make(true);
        }

        return view('vrc::portal_accounts.index');
    }

    public function store(Request $request)
    {
        $this->guard('vrc.portal.manage');

        $data = $this->validate($request, [
            'name'            => 'required|string|max:191',
            'phone'           => 'required|string|max:30',
            'email'           => 'nullable|email|max:120',
            'erp_customer_id' => 'nullable|integer',
        ]);

        $exists = VrcPortalOwner::where('business_id', $this->businessId())->where('phone', $data['phone'])->exists();
        if ($exists) {
            return back()->with('status', 'An account with that phone already exists.');
        }

        VrcPortalOwner::create($data + ['business_id' => $this->businessId(), 'is_active' => true]);

        return back()->with('status', 'Portal account created.');
    }

    public function toggle($id)
    {
        $this->guard('vrc.portal.manage');
        $owner = VrcPortalOwner::where('business_id', $this->businessId())->findOrFail($id);
        $owner->update(['is_active' => ! $owner->is_active]);

        return back()->with('status', 'Account updated.');
    }
}
