<?php

namespace App\Http\Controllers;

use App\Models\Job;
use App\Models\JobAlert;
use App\Models\SavedJob;
use App\Models\JobCategory;
use Illuminate\Http\Request;
use App\Models\JobApplication;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\JobResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\JobCategoryResource;
use Illuminate\Support\Facades\Notification;
use App\Http\Resources\JobApplicationResource;

class JobController extends Controller
{
    /**
     * Create a new job listing.
     */
    public function createJob(Request $request)
    {
        // Convert numeric fields
        $request->merge([
            'minimum_salary' => is_numeric($request->input('minimum_salary')) ? (int) $request->input('minimum_salary') : null,
            'maximum_salary' => is_numeric($request->input('maximum_salary')) ? (int) $request->input('maximum_salary') : null,
            'experience_years' => is_numeric($request->input('experience_years')) ? (int) $request->input('experience_years') : null,
        ]);

        // Validation
        $validated = $request->validate([
            // Existing validations
            'job_title' => 'required|string|max:255',
            'job_description' => 'required|string',

            'category_id' => 'required|exists:job_categories,id',
            'minimum_salary' => 'required|integer|min:0',
            'maximum_salary' => 'required|integer|min:0|gte:minimum_salary',
            'currency' => 'required|string|max:10',
            // 'salary_date' => 'required|date',
            'experience_years' => 'required|integer|min:0',
            'company_name' => 'required|string|max:255',
            'job_type' => 'required|in:full-time,part-time,contract,internship,temporary,freelance',
            // 'expiry_date' => 'required|date|after:today',

            // New validations
            'company_website' => 'nullable|url|max:255',
            'company_logo' => 'nullable|image|max:2048', // 2MB max
            'work_location_type' => 'required|in:onsite,remote,hybrid',
            'city' => 'required_if:work_location_type,onsite,hybrid|string|max:255',
            'state' => 'required_if:work_location_type,onsite,hybrid|string|max:255',
            'country' => 'required_if:work_location_type,onsite,hybrid|string|max:255',
            'key_responsibilities' => 'nullable',
            'requirements' => 'nullable',
            'positions_available' => 'nullable|integer|min:1',
            'education_level' => 'nullable|string|in:high_school,associates,bachelors,masters,doctorate,certification',
            'application_method' => 'required|in:platform,email,website',
            'application_email' => 'required_if:application_method,email|max:255',
            'application_url' => 'required_if:application_method,website|url|max:255',
            'required_documents' => 'required|array|min:1',
            'required_documents.*' => 'in:resume,cover_letter,portfolio,references',
            'benefits' => 'nullable',
            'skills' => 'nullable|array',
            'skills.*' => 'string|max:255',
            'languages' => 'nullable',
            'screening_questions' => 'nullable|array',
            'screening_questions.*' => 'string|min:10',
            // 'salary_display' => 'required|in:show,hide',
            'status' => 'required|in:draft,pending,approved,rejected',
        ]);

        // Handle file upload if company logo is provided
        if ($request->hasFile('company_logo')) {
            $path = $request->file('company_logo')->store('company_logos', 'public');
            $validated['company_logo'] = $path;
        }

        // Create the job
        $job = Job::create(array_merge($validated, [
            'user_id' => Auth::id(),
            // Convert array fields to JSON
            'key_responsibilities' => json_encode($request->input('key_responsibilities', [])),
            'requirements' => json_encode($request->input('requirements', [])),
            'required_documents' => json_encode($request->input('required_documents', [])),
            'benefits' => json_encode($request->input('benefits', [])),
            'skills' => json_encode($request->input('skills', [])),
            'languages' => json_encode($request->input('languages', [])),
            'screening_questions' => json_encode($request->input('screening_questions', []))
        ]));

        return response()->json([
            'status' => 201,
            'message' => 'Job created successfully',
            'data' => new JobResource($job)
        ], 200);
    }

    /**
     * Fetch all jobs with enhanced filtering & sorting.
     */
    public function getJobs(Request $request)
    {
        try {
            $limit = $request->input('limit', 10);
            $offset = $request->input('offset', 0);
            $sortBy = $this->validateSortField($request->input('sort_by', 'created_at'));
            $sortOrder = $request->input('sort_order', 'desc');

            // Enhanced filtering parameters
            $filters = [
                'category_id' => $request->input('category_id'),
                'job_type' => $request->input('job_type'),
                'work_location_type' => $request->input('work_location_type'),
                'location' => $request->input('location'),
                'city' => $request->input('city'),
                'state' => $request->input('state'),
                'country' => $request->input('country'),
                'min_salary' => $request->input('min_salary'),
                'max_salary' => $request->input('max_salary'),
                'currency' => $request->input('currency'),
                'keyword' => $request->input('keyword'),
                'status' => $request->input('status', 'approved'),
                'experience_years' => $request->input('experience_years'),
                'education_level' => $request->input('education_level'),
                'is_urgent_hiring' => $request->boolean('is_urgent_hiring'),
                'is_featured' => $request->boolean('is_featured'),
                'posted_within' => $request->input('posted_within'),
                'skills' => $request->input('skills'),
                'benefits' => $request->input('benefits'),
            ];

            $query = Job::with(['category', 'user'])
                ->when($filters['category_id'], fn($query) => $query->where('category_id', $filters['category_id']))
                ->when($filters['job_type'], fn($query) => $query->where('job_type', $filters['job_type']))
                ->when($filters['work_location_type'], fn($query) => $query->where('work_location_type', $filters['work_location_type']))
                ->when($filters['city'], fn($query) => $query->where('city', 'LIKE', "%{$filters['city']}%"))
                ->when($filters['state'], fn($query) => $query->where('state', 'LIKE', "%{$filters['state']}%"))
                ->when($filters['country'], fn($query) => $query->where('country', $filters['country']))
                ->when($filters['min_salary'], fn($query) => $query->where('minimum_salary', '>=', $filters['min_salary']))
                ->when($filters['max_salary'], fn($query) => $query->where('maximum_salary', '<=', $filters['max_salary']))
                ->when($filters['currency'], fn($query) => $query->where('currency', $filters['currency']))
                ->when($filters['experience_years'], fn($query) => $query->where('experience_years', '<=', $filters['experience_years']))
                ->when($filters['education_level'], fn($query) => $query->where('education_level', $filters['education_level']))
                ->when($filters['is_urgent_hiring'], fn($query) => $query->where('is_urgent_hiring', true))
                ->when($filters['is_featured'], fn($query) => $query->where('is_featured', true))
                ->when($filters['keyword'], function ($query) use ($filters) {
                    return $query->where(function ($q) use ($filters) {
                        $keyword = $filters['keyword'];
                        $q->where('job_title', 'LIKE', "%{$keyword}%")
                            ->orWhere('job_description', 'LIKE', "%{$keyword}%")
                            ->orWhere('company_name', 'LIKE', "%{$keyword}%")
                            ->orWhereRaw("JSON_SEARCH(LOWER(skills), 'one', LOWER(?)) IS NOT NULL", ["%{$keyword}%"]);
                    });
                })
                ->when($filters['skills'], function ($query) use ($filters) {
                    $skills = is_array($filters['skills']) ? $filters['skills'] : [$filters['skills']];
                    return $query->where(function ($q) use ($skills) {
                        foreach ($skills as $skill) {
                            $q->whereRaw('JSON_CONTAINS(skills, ?)', ['"' . $skill . '"']);
                        }
                    });
                })
                ->when($filters['benefits'], function ($query) use ($filters) {
                    $benefits = is_array($filters['benefits']) ? $filters['benefits'] : [$filters['benefits']];
                    return $query->where(function ($q) use ($benefits) {
                        foreach ($benefits as $benefit) {
                            $q->whereRaw('JSON_CONTAINS(benefits, ?)', ['"' . $benefit . '"']);
                        }
                    });
                })
                ->when($filters['posted_within'], function ($query) use ($filters) {
                    $days = match ($filters['posted_within']) {
                        '24h' => 1,
                        '7d' => 7,
                        '30d' => 30,
                        default => null
                    };
                    if ($days) {
                        return $query->where('created_at', '>=', now()->subDays($days));
                    }
                })
                ->where('expiry_date', '>', now());

            $total = $query->count();

            $jobs = $query->orderBy($sortBy, $sortOrder)
                ->offset($offset)
                ->limit($limit)
                ->get();
            /*
                ->toSql();
                $bindings = $query->getBindings();
                $fullQuery = vsprintf(str_replace('?', "'%s'", $jobs), $bindings);
                dd($fullQuery);
                */




            return response()->json([
                'status' => 200,
                'message' => 'Jobs fetched successfully',
                'data' => JobResource::collection($jobs),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching jobs',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Fetch detailed job information with related data.
     */
    public function getJobDetail($id)
    {
        try {
            $job = Job::with([
                'category',
                'user',
                'applications' => function ($query) {
                    $query->select('id', 'job_id', 'status', 'created_at');
                },
                'similarJobs' => function ($query) use ($id) {
                    $query->where('id', '!=', $id)
                        ->where('status', 'approved')
                        ->where('expiry_date', '>', now())
                        ->limit(5);
                }
            ])->findOrFail($id);

            // Update view count
            $job->increment('views');

            // Check if job is expired
            if ($job->expiry_date < now() && $job->status !== 'expired') {
                $job->update(['status' => 'expired']);
            }

            return response()->json([
                'status' => 200,
                'message' => 'Job details fetched successfully',
                'data' => new JobResource($job)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching job details',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Enhanced job application process.
     */
    public function applyJob(Request $request)
    {
        try {
            $validated = $request->validate([
                'job_id' => 'required|exists:jobs,id',
                'phone' => 'required|string|max:20',
                'position' => 'nullable|string|max:255',
                'cv_file' => 'required|file|mimes:pdf,doc,docx|max:2048',
                'cover_letter' => 'nullable|string|max:2000',
                'portfolio_url' => 'nullable|url|max:255',
                'linkedin_url' => 'nullable|url|max:255',
                'expected_salary' => 'nullable|numeric|min:0',
                'notice_period' => 'nullable|integer|min:0',
                'additional_information' => 'nullable|string|max:1000',
                'screening_answers' => 'nullable|array'
            ]);

            // Check if user has already applied
            $existingApplication = JobApplication::where('user_id', Auth::id())
                ->where('job_id', $validated['job_id'])
                ->exists();

            if ($existingApplication) {
                return response()->json([
                    'status' => 202,
                    'status' => 'error',
                    'message' => 'You have already applied for this job'
                ], 200);
            }

            // Check if job is still accepting applications
            $job = Job::find($validated['job_id']);
            if (!$job || $job->expiry_date < now() || $job->status !== 'approved') {
                return response()->json([
                    'status' => 403,
                    'status' => 'error',
                    'message' => 'This job is no longer accepting applications'
                ], 200);
            }

            // Handle file upload
            if ($request->hasFile('cv_file')) {
                $validated['cv_file'] = $request->file('cv_file')->store('cv_files', 'public');
            }

            // Add user ID and initial status
            $validated['user_id'] = Auth::id();
            $validated['status'] = 'pending';
            $validated['screening_answers'] = json_encode($request->input('screening_answers', []));

            $application = JobApplication::create($validated);
            Notification::create([
                'from_user_id' => Auth::id(),
                'to_user_id' => $job->user_id,
                'type' => 'job_applied',
                'text' => 'applied for job',
                'job_id' => $job->id,
            ]);


            return response()->json([
                'status' => 201,
                'message' => 'Application submitted successfully',
                'data' => new JobApplicationResource($application)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error submitting application',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Enhanced application withdrawal with validation.
     */
    public function withdrawApplication($id)
    {
        try {
            $application = JobApplication::where('id', $id)
                ->where('user_id', Auth::id())
                ->first();

            if (!$application) {
                return response()->json([
                    'status' => 403,
                    'message' => 'Application not found or unauthorized'
                ], 200);
            }

            // Check if withdrawal is allowed (e.g., within 24 hours)
            if ($application->created_at < now()->subHours(24) && $application->status !== 'pending') {
                return response()->json([
                    'status' => 422,
                    'message' => 'Application cannot be withdrawn at this stage'
                ], 200);
            }

            // Delete CV file if exists
            if ($application->cv_file) {
                Storage::disk('public')->delete($application->cv_file);
            }

            $application->delete();

            return response()->json([
                'status' => 200,
                'message' => 'Application withdrawn successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error withdrawing application',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Enhanced fetch of user's applications with filters.
     */
    public function getMyApplications(Request $request)
    {
        try {
            $status = $request->input('status');
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');

            $query = JobApplication::where('user_id', Auth::id())
                ->with(['job.category', 'job.user'])
                ->when($status, fn($query) => $query->where('status', $status))
                ->orderBy($sortBy, $sortOrder);

            // Add pagination
            $applications = $query->paginate($request->input('per_page', 10));

            return response()->json([
                'status' => 200,
                'message' => 'Applications fetched successfully',
                'data' => JobResource::collection($applications),
                'meta' => [
                    'current_page' => $applications->currentPage(),
                    'last_page' => $applications->lastPage(),
                    'per_page' => $applications->perPage(),
                    'total' => $applications->total()
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching applications',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Enhanced fetch of job applicants with filters and sorting.
     */
    public function appliedCandidates(Request $request, $id)
    {

        try {
            // Verify if user has permission to view applicants
            $job = Job::where('id', $id)
                ->where('user_id', Auth::id())
                ->firstOrFail();

            $status = $request->input('status');
            $sortBy = $request->input('sort_by', 'created_at');
            $sortOrder = $request->input('sort_order', 'desc');
            $search = $request->input('search');

            $query = JobApplication::where('job_id', $id)
                ->with(['user' => function ($query) {
                    $query->select('id', 'name', 'email', 'avatar');
                }])
                ->when($status, fn($query) => $query->where('status', $status))
                ->when($search, function ($query) use ($search) {
                    $query->whereHas('user', function ($q) use ($search) {
                        $q->where('name', 'LIKE', "%{$search}%")
                            ->orWhere('email', 'LIKE', "%{$search}%");
                    });
                })
                ->orderBy($sortBy, $sortOrder);

            $applications = $query->paginate($request->input('per_page', 10));

            return response()->json([
                'status' => 200,
                'message' => 'Candidates fetched successfully',
                'data' => JobApplicationResource::collection($applications),
                'meta' => [
                    'current_page' => $applications->currentPage(),
                    'last_page' => $applications->lastPage(),
                    'per_page' => $applications->perPage(),
                    'total' => $applications->total()
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching candidates',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Helper function to validate sort fields
     */
    private function validateSortField($field)
    {
        $allowedFields = [
            'created_at',
            'updated_at',
            'job_title',
            'company_name',
            'minimum_salary',
            'maximum_salary',
            'experience_years',
            'expiry_date',
            'views',
            'status'
        ];

        return in_array($field, $allowedFields) ? $field : 'created_at';
    }

    /**
     * Update application status
     */
    public function updateApplicationStatus(Request $request, $applicationId)
    {
        try {
            $validated = $request->validate([
                'status' => 'required|in:pending,shortlisted,interviewed,rejected,hired',
                'feedback' => 'nullable|string|max:1000'
            ]);

            $application = JobApplication::whereHas('job', function ($query) {
                $query->where('user_id', Auth::id());
            })->findOrFail($applicationId);

            $application->update([
                'status' => $validated['status'],
                'feedback' => $validated['feedback'] ?? $application->feedback
            ]);

            // Notify the applicant about status change
            // Implementation depends on your notification system

            return response()->json([
                'status' => 200,
                'message' => 'Application status updated successfully',
                'data' => new JobApplicationResource($application)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error updating application status',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Get job statistics
     */
    public function getJobStats($jobId)
    {
        try {
            $job = Job::where('user_id', Auth::id())
                ->find($jobId);

            if (!$job) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Job not found.'
                ], 200);
            }

            $stats = [
                'total_views' => $job->views,
                'total_applications' => $job->applications()->count(),
                'applications_by_status' => [
                    'pending' => $job->applications()->where('status', 'pending')->count(),
                    'shortlisted' => $job->applications()->where('status', 'shortlisted')->count(),
                    'interviewed' => $job->applications()->where('status', 'interviewed')->count(),
                    'rejected' => $job->applications()->where('status', 'rejected')->count(),
                    'hired' => $job->applications()->where('status', 'hired')->count()
                ],
                'daily_applications' => $job->applications()
                    ->select(DB::raw('DATE(created_at) as date'), DB::raw('COUNT(*) as count'))
                    ->groupBy('date')
                    ->orderBy('date', 'desc')
                    ->limit(30)
                    ->get(),
                'conversion_rate' => $job->views > 0
                    ? round(($job->applications()->count() / $job->views) * 100, 2)
                    : 0
            ];

            return response()->json([
                'status' => 200,
                'message' => 'Job statistics fetched successfully',
                'data' => $stats
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching job statistics',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Toggle job status (active/inactive)
     */
    public function toggleJobStatus($jobId)
    {
        try {
            $job = Job::where('user_id', Auth::id())
                ->findOrFail($jobId);

            $newStatus = $job->status === 'approved' ? 'inactive' : 'approved';

            $job->update(['status' => $newStatus]);

            return response()->json([
                'status' => 200,
                'message' => 'Job status updated successfully',
                'data' => new JobResource($job)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error updating job status',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Update job expiry date
     */
    public function updateJobExpiry(Request $request, $jobId)
    {
        try {
            $validated = $request->validate([
                'expiry_date' => 'required|date|after:today'
            ]);

            $job = Job::where('user_id', Auth::id())
                ->findOrFail($jobId);

            $job->update([
                'expiry_date' => $validated['expiry_date'],
                'status' => 'approved' // Reactivate if was expired
            ]);

            return response()->json([
                'status' => 200,
                'message' => 'Job expiry date updated successfully',
                'data' => new JobResource($job)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error updating job expiry',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Get recommended jobs based on user profile and history
     */
    public function getRecommendedJobs(Request $request)
    {
        try {
            $user = Auth::user();
            $limit = $request->input('limit', 10);

            // Get user's skills and previous applications
            $userApplications = JobApplication::where('user_id', $user->id)
                ->with('job')
                ->get();

            $appliedJobIds = $userApplications->pluck('job_id')->toArray();
            $userSkills = $user->skills ?? [];
            $preferredCategories = $userApplications->pluck('job.category_id')->unique()->toArray();

            // Build recommendation query
            $query = Job::with(['category', 'user'])
                ->where('status', 'approved')
                ->where('expiry_date', '>', now())
                ->whereNotIn('id', $appliedJobIds);

            // Match by skills if available
            if (!empty($userSkills)) {
                $query->where(function ($q) use ($userSkills) {
                    foreach ($userSkills as $skill) {
                        $q->orWhereRaw('JSON_CONTAINS(skills, ?)', ['"' . $skill . '"']);
                    }
                });
            }

            // Match by preferred categories
            if (!empty($preferredCategories)) {
                $query->orWhereIn('category_id', $preferredCategories);
            }

            $recommendedJobs = $query->limit($limit)->get();

            return response()->json([
                'status' => 200,
                'message' => 'Recommended jobs fetched successfully',
                'data' => JobResource::collection($recommendedJobs)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching recommended jobs',
                'error' => $e->getMessage()
            ], 200);
        }
    }


    // In JobController.php
    public function getDashboardStats()
    {
        try {
            $stats = [
                'total_jobs' => Job::where('status', 'approved')
                    ->where('expiry_date', '>', now())
                    ->count(),

                'applied_jobs' => Auth::check() ?
                    JobApplication::where('user_id', Auth::id())->count() : 0,

                'saved_jobs' => Auth::check() ?
                    SavedJob::where('user_id', Auth::id())->count() : 0,

                'job_alerts' => Auth::check() ?
                    JobAlert::where('user_id', Auth::id())->count() : 0,

                'job_types_count' => [
                    'full-time' => Job::where('job_type', 'full-time')
                        ->where('status', 'approved')
                        ->where('expiry_date', '>', now())
                        ->count(),
                    'part-time' => Job::where('job_type', 'part-time')
                        ->where('status', 'approved')
                        ->where('expiry_date', '>', now())
                        ->count(),
                    'contract' => Job::where('job_type', 'contract')
                        ->where('status', 'approved')
                        ->where('expiry_date', '>', now())
                        ->count(),
                    'internship' => Job::where('job_type', 'internship')
                        ->where('status', 'approved')
                        ->where('expiry_date', '>', now())
                        ->count(),
                ],

                'remote_jobs' => Job::where('work_location_type', 'remote')
                    ->where('status', 'approved')
                    ->where('expiry_date', '>', now())
                    ->count()
            ];

            return response()->json([
                'status' => 200,
                'message' => 'Stats fetched successfully',
                'data' => $stats
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching stats',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    public function saveJob(Request $request)
    {
        try {
            $validated = $request->validate([
                'job_id' => 'required|exists:jobs,id'
            ]);

            // Check if already saved
            $exists = SavedJob::where('user_id', Auth::id())
                ->where('job_id', $validated['job_id'])
                ->exists();

            if ($exists) {
                return response()->json([
                    'status' => 400,
                    'message' => 'Job already saved'
                ], 200);
            }

            // Save the job
            SavedJob::create([
                'user_id' => Auth::id(),
                'job_id' => $validated['job_id']
            ]);

            return response()->json([
                'status' => 200,
                'message' => 'Job saved successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error saving job',
                'error' => $e->getMessage()
            ], 200);
        }
    }
    public function getSavedJobs(Request $request)
    {
        try {
            // Fetch saved jobs with the related job details
            $savedJobs = SavedJob::with('job')
                ->where('user_id', Auth::id())
                ->get();

            return response()->json([
                'status' => 200,
                'message' => 'Saved jobs fetched successfully',
                'data' => $savedJobs
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching saved jobs',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    /**
     * Get all job categories.
     */
    public function getJobCategories(Request $request)
    {
        $categories = JobCategory::all(); // Fetch all job categories

        return response()->json([
            'status' => 200,
            'message' => 'Job categories fetched successfully.',
            'data' => $categories,
        ], 200);
    }

    /**
     * Get trending keywords for job search
     */
    public function getTrendingKeywords(Request $request)
    {
        try {
            // This could be enhanced to get actual trending keywords from search logs
            // For now, returning some common job-related keywords
            $trendingKeywords = [
                'Software Developer',
                'Marketing Manager',
                'Data Analyst',
                'Project Manager',
                'Sales Representative',
                'Graphic Designer',
                'Accountant',
                'Nurse',
                'Teacher',
                'Engineer',
                'Remote',
                'Full-time',
                'Part-time'
            ];

            return response()->json([
                'status' => 200,
                'message' => 'Trending keywords fetched successfully',
                'data' => $trendingKeywords
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching trending keywords',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    public function getJobDetailById($id)
    {
        $job = Job::with(['category', 'user', 'applications']) // Eager load related data
            ->find($id);

        if (!$job) {
            return response()->json([
                'status' => 404,
                'message' => 'Job not found',
                'data' => null,
            ], 200);
        }

        return response()->json([
            'status' => 200,
            'message' => 'Job details fetched successfully',
            'data' => new JobResource($job), // Use JobResource for structured response
        ], 200);
    }

    /**
     * Fetch jobs created by the authenticated user.
     */
    public function getMyJobs(Request $request)
    {
        try {
            $limit = $request->input('limit', 10);
            $offset = $request->input('offset', 0);
            $sortBy = $this->validateSortField($request->input('sort_by', 'created_at'));
            $sortOrder = $request->input('sort_order', 'desc');
            $status = $request->input('status');

            $query = Job::where('user_id', Auth::id())
                ->when($status, function ($query) use ($status) {
                    return $query->where('status', $status);
                });

            $total = $query->count();

            $jobs = $query->orderBy($sortBy, $sortOrder)
                ->offset($offset)
                ->limit($limit)
                ->get();

            return response()->json([
                'status' => 200,
                'message' => 'Your jobs fetched successfully',
                'data' => JobResource::collection($jobs),
                'meta' => [
                    'total' => $total,
                    'offset' => $offset,
                    'limit' => $limit,
                    'has_more' => ($offset + $limit) < $total
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Error fetching your jobs',
                'error' => $e->getMessage()
            ], 200);
        }
    }
}
