<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\MediaRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class AdminProfileController extends Controller
{
    /**
     * Show the admin profile page.
     */
    public function index()
    {
        $admin = Auth::user();

        return view('admin.profile.index', compact('admin'));
    }

    /**
     * Update the admin profile.
     */
    public function update(Request $request)
    {
        $admin = Auth::user();

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email,'.$admin->id],
            'phone_no' => ['nullable', 'string', 'max:255'],
            'profile_photo' => ['nullable', 'image', 'max:2048'],
        ]);

        $data = $request->except('profile_photo');

        if ($request->hasFile('profile_photo')) {
            $media = MediaRepository::storeByRequest($request->file('profile_photo'), 'profile_photos');
            $admin->profile_photo_id = $media->id;
        }

        $admin->update($data);

        return redirect()->route('admin.profile.index')
            ->with('success', __('Profile updated successfully.'));
    }

    /**
     * Show the change password page.
     */
    public function changePassword()
    {
        return view('admin.profile.change-password');
    }

    /**
     * Update the admin password.
     */
    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => ['required', 'current_password'],
            'password' => ['required', 'confirmed', Password::defaults()],
        ], [
            'current_password.current_password' => __('The provided password does not match your current password.'),
        ]);

        $admin = Auth::user();
        $admin->update(['password' => Hash::make($request->password)]);

        return redirect()->route('admin.profile.index')
            ->with('success', __('Password changed successfully.'));
    }
}
