<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class AdminProfileController extends Controller
{
    /**
     * Show Admin Profile
     */
    public function show()
    {
        $admin = auth('admin')->user();

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

    /**
     * Edit Profile Page
     */
    public function edit()
    {
        $admin = auth('admin')->user();

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

    /**
     * Update Profile
     */
    public function updateProfile(Request $request)
    {
        $admin = auth('admin')->user();

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('admins', 'email')->ignore($admin->id),
            ],
            'photo' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
            'cropped_photo' => ['nullable', 'string'],
        ]);

        $photoPath = $admin->photo;

        /*
        |--------------------------------------------------------------------------
        | Shared Hosting Safe Upload Path
        |--------------------------------------------------------------------------
        | Store directly inside public/uploads/admin_photos
        | So image URL works via asset($path)
        */
        $uploadDir = public_path('uploads/admin_photos');

        if (!File::exists($uploadDir)) {
            File::makeDirectory($uploadDir, 0755, true, true);
        }

        /**
         * If cropped image exists (base64)
         */
        if (!empty($validated['cropped_photo'])) {
            // delete old photo if exists
            $this->deleteOldPhoto($photoPath);

            $imageData = $validated['cropped_photo'];

            if (preg_match('/^data:image\/(\w+);base64,/', $imageData, $type)) {
                $imageData = substr($imageData, strpos($imageData, ',') + 1);
                $type = strtolower($type[1]);

                if (!in_array($type, ['jpg', 'jpeg', 'png', 'webp'])) {
                    return back()->withErrors([
                        'photo' => 'Invalid cropped image type.'
                    ])->withInput();
                }
            } else {
                return back()->withErrors([
                    'photo' => 'Invalid cropped image data.'
                ])->withInput();
            }

            $imageData = str_replace(' ', '+', $imageData);
            $decodedImage = base64_decode($imageData);

            if ($decodedImage === false) {
                return back()->withErrors([
                    'photo' => 'Failed to decode cropped image.'
                ])->withInput();
            }

            // Save cropped image as png for consistency
            $fileName = Str::uuid() . '.png';
            $fullPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

            file_put_contents($fullPath, $decodedImage);

            // DB path (public relative path)
            $photoPath = 'uploads/admin_photos/' . $fileName;
        }

        /**
         * Normal image upload
         */
        elseif ($request->hasFile('photo')) {
            // delete old photo if exists
            $this->deleteOldPhoto($photoPath);

            $file = $request->file('photo');
            $extension = strtolower($file->getClientOriginalExtension());

            if (!in_array($extension, ['jpg', 'jpeg', 'png', 'webp'])) {
                return back()->withErrors([
                    'photo' => 'Only jpg, jpeg, png, and webp are allowed.'
                ])->withInput();
            }

            $fileName = Str::uuid() . '.' . $extension;
            $file->move($uploadDir, $fileName);

            // DB path (public relative path)
            $photoPath = 'uploads/admin_photos/' . $fileName;
        }

        /**
         * Update admin
         */
        $admin->update([
            'name'  => $validated['name'],
            'email' => $validated['email'],
            'photo' => $photoPath,
        ]);

        return back()->with('success', 'Profile updated successfully!');
    }

    /**
     * Update Password
     */
    public function updatePassword(Request $request)
    {
        $admin = auth('admin')->user();

        $validated = $request->validate([
            'current_password' => ['required'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        /**
         * Check current password
         */
        if (!Hash::check($validated['current_password'], $admin->password)) {
            return back()->with('error', 'Current password is incorrect!');
        }

        /**
         * Update password
         */
        $admin->update([
            'password' => Hash::make($validated['password']),
        ]);

        return back()->with('success', 'Password updated successfully!');
    }

    /**
     * Delete old photo from public path
     */
    private function deleteOldPhoto(?string $photoPath): void
    {
        if (!$photoPath) {
            return;
        }

        $fullPath = public_path($photoPath);

        if (File::exists($fullPath) && File::isFile($fullPath)) {
            File::delete($fullPath);
        }
    }
}