<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\EmployerProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class EmployerProfileController extends Controller
{
    /**
     * Get the authenticated employer's profile details.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProfile(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

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

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

            return response()->json([
                'success' => true,
                'data' => [
                    'profile' => $employerProfile
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Employer Get Profile Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching the profile.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Update the authenticated employer's profile details.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateProfile(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $employer->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',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error.',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            // Check current password if new password is provided
            if ($request->filled('new_password')) {
                if (!Hash::check($request->current_password, $employer->password)) {
                    return response()->json([
                        'success' => false,
                        'message' => 'The provided current password does not match.',
                        'errors' => [
                            'current_password' => ['The provided password does not match your current password.']
                        ]
                    ], 422);
                }
            }

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

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

            // Update password if present
            if ($request->filled('new_password')) {
                $employer->update([
                    'password' => Hash::make($request->new_password),
                ]);
            }

            $employerProfile = [
                'name' => $employer->name,
                'email' => $employer->email,
                'company_name' => $profile->company_name,
                'phone' => $profile->phone,
                'language' => $profile->language,
                'notifications' => (bool)$profile->notifications,
                'verification_status' => $profile->verification_status ?? 'approved',
            ];

            return response()->json([
                'success' => true,
                'message' => 'Profile updated successfully.',
                'data' => [
                    'profile' => $employerProfile
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Employer Update Profile Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while updating the profile.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
