<?php

namespace App\Http\Controllers;

use App\Models\JobApplication;
use App\Models\Job;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Notifications\GeneralNotification;
use App\Services\AdminNotificationService;

class JobApplicationController extends Controller
{
    /**
     * Submit a job application
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'job_id' => 'required|exists:job_postings,id',
            'cover_letter' => 'required|string'
        ]);

        $user = Auth::user();
        $job = Job::find($request->job_id);

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

        if ($job->status !== 'approved') {
            return response()->json([
                'status' => 'error',
                'message' => 'This job is not available for applications'
            ], 400);
        }

        // Check if user already applied
        $existingApplication = JobApplication::where('job_id', $request->job_id)
            ->where('applicant_id', $user->id)
            ->first();

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

        $application = new JobApplication;
        $application->job_id = $request->job_id;
        $application->applicant_id = $user->id;
        $application->cover_letter = $request->cover_letter;
        $application->status = 'pending';
        $application->save();

        // Send admin notification
        AdminNotificationService::newJobApplicationRequest($application);

        // Notify user
        $notification_details = [
            'title' => 'Application Submitted',
            'content' => 'Your application for "' . $job->job_title . '" has been submitted and is pending admin review.',
            'mail_content' => "Dear " . $user->name . ", <br/><br/> Your application for \"" . $job->job_title . "\" at " . $job->company_name . " has been submitted successfully. It is pending admin review.<br/><br/>Thank you.",
            'url' => '/apply-for-job'
        ];
        $activity = (object)$notification_details;
        $user->notify(new GeneralNotification($activity));

        return response()->json([
            'status' => 'success',
            'message' => 'Application submitted successfully. It is pending admin review.',
            'application' => $application->load(['job', 'applicant'])
        ], 200);
    }

    /**
     * Get all job applications for admin
     *
     * @return \Illuminate\Http\Response
     */
    public function getAllApplications()
    {
        $applications = JobApplication::orderByDesc('created_at')
            ->with(['job.employer', 'applicant'])
            ->get();

        return response()->json([
            'status' => 'success',
            'applications' => $applications
        ], 200);
    }

    /**
     * Admin review job application (approve/reject)
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function reviewApplication(Request $request, $id)
    {
        $request->validate([
            'action' => 'required|in:approved,rejected',
            'admin_notes' => 'nullable|string'
        ]);

        $application = JobApplication::find($id);
        if (!$application) {
            return response()->json([
                'status' => 'error',
                'message' => 'Application not found'
            ], 404);
        }

        if ($application->status !== 'pending') {
            return response()->json([
                'status' => 'error',
                'message' => 'Application has already been processed'
            ], 400);
        }

        $applicant = $application->applicant;
        $job = $application->job;

        $application->status = $request->action;
        $application->admin_notes = $request->admin_notes;
        $application->processed_at = now();
        $application->save();

        // Notify applicant
        $notificationTitle = $request->action === 'approved' ? 'Application Approved' : 'Application Rejected';
        $notificationContent = $request->action === 'approved'
            ? 'Your application for "' . $job->job_title . '" at ' . $job->company_name . ' has been approved.'
            : 'Your application for "' . $job->job_title . '" at ' . $job->company_name . ' has been rejected.';

        $notification_details = [
            'title' => $notificationTitle,
            'content' => $notificationContent,
            'mail_content' => "Dear " . $applicant->name . ", <br/><br/> " . $notificationContent . "<br/><br/>" . ($request->admin_notes ? "Admin Notes: " . $request->admin_notes . "<br/><br/>" : "") . "Thank you.",
            'url' => '/apply-for-job'
        ];
        $activity = (object)$notification_details;
        $applicant->notify(new GeneralNotification($activity));

        return response()->json([
            'status' => 'success',
            'message' => 'Application ' . $request->action . ' successfully',
            'application' => $application->load(['job', 'applicant'])
        ], 200);
    }

    /**
     * Get user's job applications
     *
     * @return \Illuminate\Http\Response
     */
    public function getUserApplications()
    {
        $user = Auth::user();
        
        $applications = JobApplication::where('applicant_id', $user->id)
            ->orderByDesc('created_at')
            ->with(['job.employer', 'applicant'])
            ->get();

        return response()->json([
            'status' => 'success',
            'applications' => $applications
        ], 200);
    }

    /**
     * Get specific user's job applications (for admin)
     *
     * @param  int  $userId
     * @return \Illuminate\Http\Response
     */
    public function getUserApplicationsById($userId)
    {
        $applications = JobApplication::where('applicant_id', $userId)
            ->orderByDesc('created_at')
            ->with(['job.employer', 'applicant'])
            ->get();

        return response()->json([
            'status' => 'success',
            'applications' => $applications
        ], 200);
    }
}
