<?php

use App\Actions\Fortify\PasswordValidationRules;
use App\Facades\Vrm\MediaForge;
use App\Models\User;
use App\Traits\Vrm\Livewire\WithNotifications;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;

return new class extends Component {
    use PasswordValidationRules;
    use WithFileUploads;
    use WithNotifications;

    // Admin ID
    public $admin_id;

    // User
    public $user;

    // Path to upload the photo
    public $uploadedPath = 'admin-users';

    #[Validate('required|string|max:255')]
    public $name = '';

    #[Validate('required|string|email|max:255')]
    public $email = '';

    #[Validate('nullable|string|max:20')]
    public $phone = '';

    #[Validate('nullable|string|max:20')]
    public $whatsapp_number = '';

    #[Validate('nullable|string')]
    public $password = '';

    #[Validate('nullable|string')]
    public $password_confirmation = '';

    #[Validate('nullable|image|mimes:jpg,jpeg,png,webp|max:2048')]
    public $photo;

    // Current Photo
    public $currentPhoto = '';

    public function mount($id): void
    {
        $this->admin_id = $id;
        $this->user = User::find($this->admin_id);

        if ($this->user) {
            $this->name = $this->user->name;
            $this->email = $this->user->email;
            $this->phone = $this->user->phone ?? '';
            $this->whatsapp_number = $this->user->getMeta('whatsapp_number') ?? '';
            $this->currentPhoto = $this->user->getMeta('photo') ?? '';
        }
    }

    // Remove photo
    public function removePhoto($photo_path): void
    {
        // From User get photo
        $_photo = $this->user->getMeta('photo');

        // Check if they match
        if ($_photo === $photo_path) {
            try {
                // Delete the photo
                MediaForge::delete($photo_path);

                // Update user
                $this->user->setMeta('photo', null);

                // Flash success message
                $this->notifySuccess(__('Photo was deleted successfully!'));
            } catch (\Exception $e) {
                $this->notifyError(__('Failed to remove photo. Please try again: ' . $e->getMessage()));
            }
        }

        // New Current Photo
        $this->currentPhoto = $this->user->getMeta('photo') ?? '';
    }

    /**
				 * Update admin user.
				 */
    public function update(): void
    {
        // Conditional validation for password
        $passwordRules = $this->passwordRules();
        if (empty($this->password)) {
            $passwordRules = ['nullable'];
        }

        // Conditional validation for picture
        $pictureRules = 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048';

        // Validate the form
        $validated = Validator::make(
            [
                'name' => $this->name,
                'email' => $this->email,
                'phone' => $this->phone,
                'whatsapp_number' => $this->whatsapp_number,
                'password' => $this->password,
                'password_confirmation' => $this->password_confirmation,
                'photo' => $this->photo,
            ],
            [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user->id)],
                'phone' => ['nullable', 'string', 'max:20'],
                'whatsapp_number' => ['nullable', 'string', 'max:20'],
                'password' => $passwordRules,
                'photo' => $pictureRules, // ✅ Remove the array wrapper
            ],
        )->validate();

        try {
            // Handle photo upload if provided
            if ($this->photo) {
                try {
                    // Check if current photo exists and delete it
                    if ($this->currentPhoto && file_exists(public_path($this->currentPhoto))) {
                        MediaForge::delete($this->currentPhoto);
                    }

                    // Upload new photo
                    $_photo = MediaForge::upload($this->photo)->useYearFolder(true)->randomizeFileName(true)->to($this->uploadedPath)->resize(400, 400)->run();

                    // Store photo in user_meta
                    $this->user->setMeta('photo', $_photo);
                    $this->currentPhoto = $_photo;
                } catch (\Exception $e) {
                    $this->notifyError(__('Failed to upload photo. Please try again: ' . $e->getMessage()));

                    return;
                }
            }

            // Update the user
            $updateData = [
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'] ?? null,
            ];

            // Only update password if provided
            if (!empty($validated['password'])) {
                $updateData['password'] = $validated['password'];
            }

            $this->user->update($updateData);

            // Store whatsapp number in user_meta
            if (!empty($validated['whatsapp_number'])) {
                $this->user->setMeta('whatsapp_number', $validated['whatsapp_number']);
            } else {
                // Remove if empty
                $this->user->setMeta('whatsapp_number', null);
            }

            // Reset photo field
            $this->reset('photo');

            // Update current values
            $this->currentPhoto = $this->user->getMeta('photo') ?? '';

            // Show success message
            $this->notifySuccess(__('Admin updated successfully!'));
        } catch (\Exception $e) {
            $this->notifyError(__('Failed to update admin. Please try again: ' . $e->getMessage()));
        }
    }

    public function cancel(): void
    {
        $this->redirect(route('admin.admins.index'));
    }

    protected function view($data = [])
    {
        return app('view')->file('/home/ziidfelj/home.ziidi.trade/storage/framework/views/livewire/views/7ce8ebb4.blade.php', $data);
    }
}; 