<?php

namespace App\Http\Controllers\Dashboard\Master;

use App\Models\Admin;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{
    public function index()
    {
        $admins = Admin::latest()->get();

        $data = [
            'title' => 'Registered Admins',
            'admins' => $admins
        ];

        return view('dashboard.master.admin.index', $data);
    }
    public function register()
    {
        $data = ['title' => 'Register Admin'];

        return view('dashboard.master.admin.register', $data);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required',
            'email' => 'required|unique:admins,email',
            'password' => 'required',
        ]);

        $data['uuid'] = Str::uuid();
        $data['live_chat_id'] = Str::uuid();
        $data['password'] = Hash::make($data['password']);

        Admin::create($data);

        return redirect()->route('master.admin.edit', $data['uuid'])->with('success', 'Admin created successfully');
    }

    public function edit(string $uuid)
    {

        $admin = Admin::where('uuid', $uuid)->first();

        $data = [
            'title' => 'Edit Admin',
            'admin' => $admin
        ];

        return view('dashboard.master.admin.edit', $data);
    }

    public function update(Request $request, string $uuid)
    {
        $admin = Admin::where('uuid', $uuid)->first();

        $request->validate([
            'name' => 'required',
            'email' => 'required|unique:admins,email,' . $admin->id,
            'password' => 'nullable',
            'smtp_user' => 'required',
            'smtp_password' => 'required',
            'smtp_host' => 'required',
            'smtp_port' => 'required',
            'smtp_encryption' => 'required',
            'status' => 'required',
            'live_chat' => 'nullable',
        ]);


        $data = [
            'name' => $request->name,
            'email' => $request->email,
            'status' => $request->status,
            'smtp_user' => $request->smtp_user,
            'smtp_password' => $request->smtp_password,
            'smtp_host' => $request->smtp_host,
            'smtp_port' => $request->smtp_port,
            'smtp_encryption' => $request->smtp_encryption,
            'live_chat' => $request->live_chat,
        ];

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        } else {
            unset($data['password']);
        }

        $admin->update($data);

        return redirect()->route('master.admin.edit', $uuid)->with('success', 'Admin updated successfully.');
    }
}
