<?php

namespace App\Http\Controllers;

use App\Models\OwnerProfile;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = Auth::user();

        if ($user->role !== 'owner') {
            abort(403);
        }

        $profile = OwnerProfile::where('user_id', $user->id)->first();

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

    public function edit()
    {
        $user = Auth::user();

        if ($user->role !== 'owner') {
            abort(403);
        }

        $profile = OwnerProfile::firstOrCreate(
            ['user_id' => $user->id],
            [
                'address'   => null,
                'instagram' => null,
                'shopee'    => null,
                'tokopedia' => null,
                'maps'      => null,
            ]
        );

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

    public function update(Request $request)
    {
        $user = User::find(Auth::id());

        if ($user->role !== 'owner') {
            abort(403);
        }

        $validated = $request->validate([
            'name'      => 'required|string|max:255',
            'email'     => 'required|email|max:255|unique:users,email,' . $user->id,
            'phone'     => 'nullable|string|max:30',
            'address'   => 'nullable|string',
            'instagram' => 'nullable|string|max:100',
            'shopee'    => 'nullable|url|max:255',
            'tokopedia' => 'nullable|url|max:255',
            'maps'      => 'nullable|string',
            'password'  => 'nullable|confirmed|min:6',
        ]);

        $user->name  = $validated['name'];
        $user->email = $validated['email'];
        $user->phone = $validated['phone'] ?? null;

        if (!empty($validated['password'])) {
            $user->password = Hash::make($validated['password']);
        }

        $user->save();

        OwnerProfile::updateOrCreate(
            ['user_id' => $user->id],
            [
                'address'   => $validated['address'] ?? null,
                'instagram' => $validated['instagram'] ?? null,
                'shopee'    => $validated['shopee'] ?? null,
                'tokopedia' => $validated['tokopedia'] ?? null,
                'maps'      => $validated['maps'] ?? null,
            ]
        );

        return redirect()
            ->route('profile.index')
            ->with('success', 'Profile berhasil diperbarui.');
    }
}