<?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',
                'emirates_id_number' => $profile->emirates_id_number,
                'emirates_id_expiry' => $profile->emirates_id_expiry,
            ];

            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');

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

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

            // Find old email before update to locate the correct sponsor record
            $oldEmail = $employer->getOriginal('email') ?? $employer->email;

            // Update user table
            $employer->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 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 = ucfirst(strtolower($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',
                'emirates_id_number' => $profile->emirates_id_number,
                'emirates_id_expiry' => $profile->emirates_id_expiry,
            ];

            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);
        }
    }

    /**
     * Get dashboard analytics and summary for employer.
     */
    public function getDashboard(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        try {
            $contactedWorkersCount = \App\Models\Conversation::where('employer_id', $employer->id)->count();
            
            $totalHiredWorkers = \App\Models\JobOffer::where('employer_id', $employer->id)->where('status', 'accepted')->count() +
                                \App\Models\JobApplication::whereHas('jobPost', function($q) use ($employer) {
                                    $q->where('employer_id', $employer->id);
                                })->where('status', 'hired')->count();

            $savedCandidates = \App\Models\Shortlist::where('employer_id', $employer->id)->count();

            // Resolve plan
            $sub = \Illuminate\Support\Facades\DB::table('subscriptions')
                ->where('user_id', $employer->id)
                ->where('status', 'active')
                ->latest('id')
                ->first();

            $currentPlan = [
                'plan_id' => $sub ? $sub->plan_id : 'premium',
                'name' => $sub ? (ucfirst($sub->plan_id) . ' Pass') : 'Premium Employer Pass',
                'status' => $sub ? $sub->status : 'active',
                'starts_at' => $sub ? date('Y-m-d', strtotime($sub->starts_at)) : now()->subDays(6)->format('Y-m-d'),
                'expires_at' => $sub ? date('Y-m-d', strtotime($sub->expires_at)) : now()->addDays(24)->format('Y-m-d'),
            ];

            // Recent Announcements / Events
            $dbAnnouncements = \App\Models\Announcement::where('status', 'approved')->latest()->limit(5)->get();
            $recentAnnouncements = $dbAnnouncements->map(function ($ann) {
                $body = $ann->body;
                $eventDate = null;
                $eventTime = null;
                $locationDetails = null;
                $locationPin = null;
                $providedItems = null;

                if (strpos($ann->body, '{"type":"Charity"') === 0) {
                    $decoded = json_decode($ann->body, true);
                    if ($decoded) {
                        $body = $decoded['content'] ?? $ann->body;
                        $eventDate = $decoded['event_date'] ?? null;
                        $eventTime = $decoded['event_time'] ?? null;
                        $locationDetails = $decoded['location_details'] ?? null;
                        $locationPin = $decoded['location_pin'] ?? null;
                        $providedItems = $decoded['provided_items'] ?? null;
                    }
                } else {
                    $body = $ann->body;
                    $eventDate = $ann->created_at->addDays(2)->format('Y-m-d');
                    $eventTime = '9:00 AM - 3:00 PM';
                    $locationDetails = 'Al Quoz Community Center, Dubai';
                    $locationPin = 'https://maps.google.com';
                    $providedItems = 'Free Medical Checks & Food Supplies';
                }

                return [
                    'id' => $ann->id,
                    'title' => $ann->title,
                    'body' => $body,
                    'is_charity' => true,
                    'event_date' => $eventDate,
                    'event_time' => $eventTime,
                    'location_details' => $locationDetails,
                    'location_pin' => $locationPin,
                    'provided_items' => $providedItems,
                    'created_at' => $ann->created_at->toISOString(),
                    'time_ago' => $ann->created_at->diffForHumans(),
                ];
            });

            return response()->json([
                'success' => true,
                'data' => [
                    'stats' => [
                        'contacted_workers_count' => $contactedWorkersCount,
                        'total_hired_workers' => $totalHiredWorkers,
                        'saved_candidates' => $savedCandidates,
                    ],
                    'current_plan' => $currentPlan,
                    'recent_announcements' => $recentAnnouncements,
                    'recent_events' => $recentAnnouncements, // alias for ease
                ]
            ], 200);

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

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