<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\JobApplication;
use App\Models\JobPosting;

class DashboardController extends Controller
{
    public function index()
    {
        $openJobsCount = JobPosting::where('status', 'published')->count();

        $thisWeekApplications = JobApplication::whereBetween('created_at', [
            now()->startOfWeek(),
            now()->endOfWeek(),
        ])->count();

        $totalApplications = JobApplication::count();

        $applicationsByDepartment = JobApplication::join('job_postings', 'job_applications.job_posting_id', '=', 'job_postings.id')
            ->selectRaw('job_postings.department, COUNT(job_applications.id) as count')
            ->groupBy('job_postings.department')
            ->orderByDesc('count')
            ->get();

        $recentApplications = JobApplication::with('jobPosting')
            ->latest()
            ->limit(10)
            ->get();

        $applicationsByStatus = JobApplication::selectRaw('status, COUNT(*) as count')
            ->groupBy('status')
            ->get()
            ->pluck('count', 'status');

        return view('admin.dashboard', compact(
            'openJobsCount',
            'thisWeekApplications',
            'totalApplications',
            'applicationsByDepartment',
            'recentApplications',
            'applicationsByStatus'
        ));
    }
}