<?php

namespace App\Http\Controllers\Employer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\User;
use App\Models\EmployerProfile;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class ProfileController extends Controller
{
    private function resolveCurrentUser()
    {
        $sess = session('user');
        $sessId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
        
        if (!$sessId) {
            $user = User::where('role', 'employer')->first();
            if ($user) {
                session(['user' => (object)[
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => 'employer',
                    'subscription_status' => $user->subscription_status ?? 'active',
                ]]);
                return $user;
            }
        } else {
            return User::find($sessId);
        }
        
        return null;
    }

    public function index(Request $request)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return redirect()->route('employer.dashboard');
        }

        // Fetch or create profile
        $profile = $user->employerProfile;
        if (!$profile) {
            $profile = EmployerProfile::create([
                'user_id' => $user->id,
                'company_name' => 'Al Mansoor Household',
                'phone' => '+971 50 123 4567',
                'emirates_id_status' => 'approved',
            ]);
        }

        $employerProfile = [
            'name' => $user->name,
            'email' => $user->email,
            'company_name' => $profile->company_name,
            'phone' => $profile->phone,
            'language' => $profile->language ?? 'English',
            'notifications' => (bool)($profile->notifications ?? true),
        ];

        return Inertia::render('Employer/Profile', [
            'employerProfile' => $employerProfile,
        ]);
    }

    public function update(Request $request)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return back()->withErrors(['general' => 'User session not found.']);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'phone' => 'required|string|max:255',
            'company_name' => 'required|string|max:255',
            'language' => 'required|string|in:English,Arabic',
            'notifications' => 'required|boolean',
            'current_password' => 'nullable|required_with:new_password|string',
            'new_password' => 'nullable|string|min:8|confirmed',
        ]);

        // Update User Model
        $user->update([
            'name' => $request->name,
            'email' => $request->email,
        ]);

        // Update EmployerProfile
        $profile = $user->employerProfile;
        if (!$profile) {
            $profile = new EmployerProfile(['user_id' => $user->id]);
        }
        $profile->company_name = $request->company_name;
        $profile->phone = $request->phone;
        $profile->language = $request->language;
        $profile->notifications = $request->notifications;
        $profile->save();

        // Update Password if provided
        if ($request->filled('new_password')) {
            if (!Hash::check($request->current_password, $user->password)) {
                return back()->withErrors(['current_password' => 'The provided password does not match your current password.']);
            }
            $user->update([
                'password' => Hash::make($request->new_password),
            ]);
        }

        // Update session user name/email
        session(['user' => (object)[
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'role' => 'employer',
            'subscription_status' => $user->subscription_status ?? 'active',
        ]]);

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