<?php

namespace Modules\VetPortal\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Modules\VetPortal\Entities\VpPortalAccount;
use App\Contact;
use Yajra\DataTables\Facades\DataTables;

class VpAccountController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (!auth()->user()->can('vet_portal.manage_accounts')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $businessId = $this->biz();
        $stats = [
            'total'   => VpPortalAccount::forBusiness($businessId)->count(),
            'enabled' => VpPortalAccount::forBusiness($businessId)->where('enabled', true)->count(),
        ];
        return view('vetPortal::accounts.index', compact('stats'));
    }

    public function list()
    {
        $this->gate();

        $query = VpPortalAccount::with('contact')->forBusiness($this->biz())->latest();

        return DataTables::of($query)
            ->addColumn('owner', fn($row) => e(optional($row->contact)->name ?? '—'))
            ->addColumn('status_badge', fn($row) => $row->enabled
                ? '<span class="label label-success">Enabled</span>'
                : '<span class="label label-default">Disabled</span>')
            ->addColumn('last_login', fn($row) => $row->last_login_at
                ? $row->last_login_at->format('d M Y H:i')
                : '<span class="text-muted">never</span>')
            ->addColumn('action', function ($row) {
                $toggle = $row->enabled
                    ? '<button class="btn btn-xs btn-warning btn-toggle-acc" data-id="' . $row->id . '">Disable</button>'
                    : '<button class="btn btn-xs btn-success btn-toggle-acc" data-id="' . $row->id . '">Enable</button>';
                $pw  = '<button class="btn btn-xs btn-primary btn-reset-acc" data-id="' . $row->id . '" data-name="' . e($row->name) . '"><i class="fa fa-key"></i></button>';
                $del = '<button class="btn btn-xs btn-danger btn-delete-acc" data-id="' . $row->id . '"><i class="fa fa-trash"></i></button>';
                return $toggle . ' ' . $pw . ' ' . $del;
            })
            ->rawColumns(['status_badge', 'last_login', 'action'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $this->gate();
        $request->validate([
            'contact_id' => 'required|integer',
            'name'       => 'required|string|max:150',
            'email'      => 'required|email|max:150|unique:vp_portal_accounts,email',
            'password'   => 'required|string|min:6',
        ]);

        $businessId = $this->biz();

        // Verify the contact belongs to this business
        $contact = Contact::where('business_id', $businessId)->find($request->contact_id);
        if (!$contact) {
            return response()->json(['success' => false, 'msg' => 'Selected pet owner not found.'], 422);
        }

        VpPortalAccount::create([
            'business_id' => $businessId,
            'contact_id'  => $contact->id,
            'name'        => $request->name,
            'email'       => strtolower(trim($request->email)),
            'password'    => Hash::make($request->password),
            'enabled'     => true,
        ]);

        return response()->json(['success' => true, 'msg' => __('vetPortal::lang.account_created')]);
    }

    public function resetPassword(Request $request, $id)
    {
        $this->gate();
        $request->validate(['password' => 'required|string|min:6']);

        $account = VpPortalAccount::forBusiness($this->biz())->findOrFail($id);
        $account->update(['password' => Hash::make($request->password)]);

        return response()->json(['success' => true, 'msg' => __('vetPortal::lang.password_reset')]);
    }

    public function toggle($id)
    {
        $this->gate();
        $account = VpPortalAccount::forBusiness($this->biz())->findOrFail($id);
        $account->update(['enabled' => !$account->enabled]);

        return response()->json(['success' => true, 'msg' => __('vetPortal::lang.updated')]);
    }

    public function destroy($id)
    {
        $this->gate();
        $account = VpPortalAccount::forBusiness($this->biz())->findOrFail($id);
        $account->delete();

        return response()->json(['success' => true, 'msg' => __('vetPortal::lang.deleted')]);
    }
}
