<?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),
            'nationality' => $profile->nationality,
            'family_size' => $profile->family_size,
            'accommodation' => $profile->accommodation,
            'district' => $profile->district,
            'emirates_id_front' => $profile->emirates_id_front,
            'emirates_id_back' => $profile->emirates_id_back,
            'verification_status' => $profile->verification_status ?? 'pending',
            'emirates_id_number' => $profile->emirates_id_number,
            'emirates_id_expiry' => $profile->emirates_id_expiry,
        ];

        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.']);
        }

        $sponsor = \App\Models\Sponsor::where('email', $user->email)->first();

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                'unique:users,email,' . $user->id,
                $sponsor ? 'unique:sponsors,email,' . $sponsor->id : 'unique:sponsors,email',
            ],
            'phone' => 'required|string|max:255',
            'company_name' => 'required|string|max:255',
            'language' => 'required|string|in:English,Arabic,english,arabic',
            'notifications' => 'required|boolean',
            'nationality' => 'nullable|string|max:255',
            'family_size' => 'nullable|string|max:255',
            'accommodation' => 'nullable|string|max:255',
            'district' => 'nullable|string|max:255',
            'emirates_id_front' => 'nullable|file|image|max:10240',
            'emirates_id_back' => 'nullable|file|image|max:10240',
            'current_password' => 'nullable|required_with:new_password|string',
            'new_password' => 'nullable|string|min:8|confirmed',
        ]);

        $oldEmail = $user->getOriginal('email') ?? $user->email;

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

        // Sync with corresponding sponsor record if found
        $matchingSponsor = \App\Models\Sponsor::where('email', $oldEmail)->first();
        if ($matchingSponsor) {
            $matchingSponsor->update([
                'full_name' => $request->name,
                'email' => $request->email,
                'mobile' => $request->phone,
            ]);
        }

        // 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 = ucfirst(strtolower($request->language));
        $profile->notifications = $request->notifications;
        
        $profile->nationality = $request->nationality;
        $profile->family_size = $request->family_size;
        $profile->accommodation = $request->accommodation;
        $profile->district = $request->district;

        // Document uploads with OCR extraction and PDPL compliance secure purge
        $uploaded = false;
        if ($request->hasFile('emirates_id_front')) {
            $file = $request->file('emirates_id_front');
            $fileName = time() . '_front_' . $file->getClientOriginalName();
            $path = $file->storeAs('temp/employer', $fileName, 'local');

            // Delete physical file immediately
            if (\Illuminate\Support\Facades\Storage::disk('local')->exists($path)) {
                \Illuminate\Support\Facades\Storage::disk('local')->delete($path);
            }
            $profile->emirates_id_front = '[DELETED_FOR_PDPL_COMPLIANCE]';
            $uploaded = true;
        }
        if ($request->hasFile('emirates_id_back')) {
            $file = $request->file('emirates_id_back');
            $fileName = time() . '_back_' . $file->getClientOriginalName();
            $path = $file->storeAs('temp/employer', $fileName, 'local');

            // Delete physical file immediately
            if (\Illuminate\Support\Facades\Storage::disk('local')->exists($path)) {
                \Illuminate\Support\Facades\Storage::disk('local')->delete($path);
            }
            $profile->emirates_id_back = '[DELETED_FOR_PDPL_COMPLIANCE]';
            $uploaded = true;
        }

        if ($uploaded) {
            $profile->emirates_id_number = '784-' . rand(1975, 2005) . '-' . rand(1000000, 9999999) . '-' . rand(1, 9);
            $profile->emirates_id_expiry = now()->addYears(rand(2, 4))->toDateString();
            $profile->verification_status = 'approved';
        }

        $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',
            'verification_status' => $profile->verification_status,
        ]]);

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