<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Job;
use App\Models\JobCategory;
use App\Models\JobApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class JobController extends Controller
{
    /**
     * Display a listing of the jobs for management.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $jobs = Job::with('category', 'user')
            ->latest()
            ->paginate(15);
        return view('admin.pages.jobs.index', compact('jobs'));
    }

    /**
     * Display the specified job details.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $job = Job::with('category', 'user')
            ->findOrFail($id);
        return view('admin.pages.jobs.show', compact('job'));
    }

    /**
     * Show the form for editing the specified job.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $job = Job::findOrFail($id);
        $categories = JobCategory::where('status', 1)->get();
        return view('admin.pages.jobs.edit', compact('job', 'categories'));
    }

    /**
     * Update the specified job status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $job = Job::findOrFail($id);
        
        $request->validate([
            'status' => 'required|in:draft,pending,approved,rejected',
            'job_title' => 'required|string|max:255',
            'job_description' => 'required|string',
            'category_id' => 'required|exists:job_categories,id',
            'expiry_date' => 'required|date',
        ]);
        
        $job->update([
            'job_title' => $request->job_title,
            'job_description' => $request->job_description,
            'category_id' => $request->category_id,
            'status' => $request->status,
            'expiry_date' => $request->expiry_date,
        ]);

        return redirect()->route('admin.jobs.index')
            ->with('success', 'Job updated successfully.');
    }

    /**
     * Remove the specified job from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $job = Job::findOrFail($id);
        
        // Delete company logo if exists
        if ($job->company_logo) {
            Storage::disk('public')->delete($job->company_logo);
        }
        
        $job->delete();
        
        return redirect()->route('admin.jobs.index')
            ->with('success', 'Job deleted successfully.');
    }

    /**
     * Display all job applications for a specific job.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function applications($id)
    {
        $job = Job::findOrFail($id);
        $applications = JobApplication::where('job_id', $id)
            ->with('user')
            ->latest()
            ->paginate(15);
            
        return view('admin.pages.jobs.applications', compact('job', 'applications'));
    }

    /**
     * Update job application status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $applicationId
     * @return \Illuminate\Http\Response
     */
    public function updateApplicationStatus(Request $request, $applicationId)
    {
        $request->validate([
            'status' => 'required|in:pending,shortlisted,rejected,hired'
        ]);

        $application = JobApplication::findOrFail($applicationId);
        $application->status = $request->status;
        $application->save();

        return redirect()->back()
            ->with('success', 'Application status updated successfully.');
    }

    /**
     * Toggle job status (active/inactive).
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleStatus($id)
    {
        $job = Job::findOrFail($id);
        $job->status = $job->status === 'approved' ? 'rejected' : 'approved';
        $job->save();

        $statusText = $job->status === 'approved' ? 'activated' : 'deactivated';
        
        return redirect()->back()
            ->with('success', "Job {$statusText} successfully.");
    }

    /**
     * Show job statistics for admin dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function stats()
    {
        // Basic job statistics for admin
        $totalJobs = Job::count();
        $activeJobs = Job::where('status', 'approved')->count();
        $pendingJobs = Job::where('status', 'pending')->count();
        $expiredJobs = Job::where('expiry_date', '<', now())->count();
        
        // Application statistics
        $totalApplications = JobApplication::count();
        $pendingApplications = JobApplication::where('status', 'pending')->count();
        $hiredCount = JobApplication::where('status', 'hired')->count();
        
        // Top categories
        $topCategories = JobCategory::withCount('jobs')
            ->orderByDesc('jobs_count')
            ->limit(5)
            ->get();

        return view('admin.pages.jobs.stats', compact(
            'totalJobs', 
            'activeJobs', 
            'pendingJobs', 
            'expiredJobs',
            'totalApplications',
            'pendingApplications',
            'hiredCount',
            'topCategories'
        ));
    }
} 