<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    public function show()
    {
        $user = Auth::user();
        $customer = $user->customer;

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

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:25|unique:users,phone,' . $user->id,
            'alternate_phone' => 'nullable|string|max:25',
            'city' => 'nullable|string|max:100',
            'district' => 'nullable|string|max:100',
            'address' => 'nullable|string|max:500',
            'preferred_contact' => 'required|in:whatsapp,call,email',
            'current_password' => 'nullable|required_with:new_password',
            'new_password' => 'nullable|min:8|confirmed',
        ]);

        $user->update([
            'name' => $validated['name'],
            'phone' => $validated['phone'],
        ]);

        if (!empty($validated['new_password'])) {
            if (!Hash::check($validated['current_password'], $user->password)) {
                return back()->withErrors(['current_password' => 'Current password is incorrect.']);
            }
            $user->update(['password' => Hash::make($validated['new_password'])]);
        }

        if ($user->customer) {
            $user->customer->update([
                'full_name' => $validated['name'],
                'phone' => $validated['phone'],
                'alternate_phone' => $validated['alternate_phone'] ?? null,
                'city' => $validated['city'] ?? 'Dhaka',
                'district' => $validated['district'] ?? 'Dhaka',
                'address' => $validated['address'] ?? null,
                'preferred_contact' => $validated['preferred_contact'],
            ]);
        }

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