<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage; 
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    /**
     * Display the user's profile form.
     */
    public function edit(Request $request): Response
    {
        return Inertia::render('Profile/Edit', [
            'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail,
            'status' => session('status'),
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $request->user()->save();

        return Redirect::route('settings.edit');
    }

    /**
     * Update Profile Images (Avatar & Cover).
     */
    public function updateImages(Request $request): RedirectResponse
    {
        $request->validate([
            'avatar'      => 'nullable|image|max:2048', // 2MB Max
            'cover_image' => 'nullable|image|max:4096', // 4MB Max
        ]);

        $user = $request->user();

        // 1. Handle Avatar Upload
        if ($request->hasFile('avatar')) {
            if ($user->avatar && str_contains($user->avatar, '/storage/')) {
                $relativePath = parse_url($user->avatar, PHP_URL_PATH);
                $cleanPath = preg_replace('/^.*?\/storage\//', '', $relativePath);
                Storage::disk('public')->delete($cleanPath);
            }

            // Store new file
            $path = $request->file('avatar')->store('avatars', 'public');
            $user->avatar = '/storage/' . $path;
        }

        // 2. Handle Cover Image Upload
        if ($request->hasFile('cover_image')) {
            if ($user->cover_image && str_contains($user->cover_image, '/storage/')) {
                $relativePath = parse_url($user->cover_image, PHP_URL_PATH);
                $cleanPath = preg_replace('/^.*?\/storage\//', '', $relativePath);
                Storage::disk('public')->delete($cleanPath);
            }

            // Store new file
            $path = $request->file('cover_image')->store('covers', 'public');
            $user->cover_image = '/storage/' . $path;
        }

        $user->save();

        return back()->with('status', 'images-updated');
    }

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validate([
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        if ($user->avatar && str_contains($user->avatar, '/storage/')) {
            $relativePath = parse_url($user->avatar, PHP_URL_PATH);
            $cleanPath = preg_replace('/^.*?\/storage\//', '', $relativePath);
            Storage::disk('public')->delete($cleanPath);
        }

        if ($user->cover_image && str_contains($user->cover_image, '/storage/')) {
            $relativePath = parse_url($user->cover_image, PHP_URL_PATH);
            $cleanPath = preg_replace('/^.*?\/storage\//', '', $relativePath);
            Storage::disk('public')->delete($cleanPath);
        }

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }
}