<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Applicant;
use App\Models\Interview;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class InterviewController extends Controller
{
    public function index()
    {
        $today = now()->toDateString();
        $todayEnd = now()->copy()->endOfDay();

        $todayInterviews = Interview::with('applicant.jobPosting')
            ->whereDate('scheduled_at', $today)
            ->where('status', 'scheduled')
            ->orderBy('scheduled_at')
            ->get();

        $upcomingInterviews = Interview::with('applicant.jobPosting')
            ->whereDate('scheduled_at', '>', $today)
            ->where('scheduled_at', '<=', now()->addDays(14)->endOfDay())
            ->where('status', 'scheduled')
            ->orderBy('scheduled_at')
            ->get();

        $followUpsDue = Interview::with(['applicant.jobPosting', 'interviewer'])
            ->where('status', 'scheduled')
            ->whereNotNull('follow_up_at')
            ->where('follow_up_at', '<=', $todayEnd)
            ->orderBy('follow_up_at')
            ->get();

        $completedInterviews = Interview::with(['applicant.jobPosting', 'interviewer'])
            ->where('status', 'completed')
            ->orderByDesc('scheduled_at')
            ->paginate(10);

        return view('recruitment.interviews.index', compact(
            'todayInterviews',
            'upcomingInterviews',
            'followUpsDue',
            'completedInterviews'
        ));
    }

    public function create()
    {
        $applicants = Applicant::orderBy('name')->get();
        $interviewers = $this->interviewers();

        return view('recruitment.interviews.create', compact('applicants', 'interviewers'));
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $request->merge([
            'follow_up_at' => $request->filled('follow_up_at') ? $request->input('follow_up_at') : null,
        ]);
        $validated = $request->validate([
            'applicant_id' => ['required', 'exists:applicants,id'],
            'interviewer_id' => ['nullable', 'exists:users,id'],
            'interview_type' => ['required', Rule::in(['video', 'in-person', 'phone'])],
            'scheduled_at' => ['required', 'date'],
            'status' => ['required', Rule::in(['scheduled', 'completed', 'cancelled'])],
            'feedback' => ['nullable', 'string'],
            'follow_up_at' => ['nullable', 'date'],
            'follow_up_notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $validated['follow_up_at'] = ! empty($validated['follow_up_at']) ? $validated['follow_up_at'] : null;

        Interview::create(array_merge($validated, [
            'company_id' => $companyId,
        ]));

        return redirect()->route('interviews.index')->with('success', 'Interview scheduled successfully.');
    }

    public function edit(Interview $interview)
    {
        $applicants = Applicant::orderBy('name')->get();
        $interviewers = $this->interviewers();

        return view('recruitment.interviews.edit', compact('interview', 'applicants', 'interviewers'));
    }

    public function update(Request $request, Interview $interview)
    {
        $request->merge([
            'follow_up_at' => $request->filled('follow_up_at') ? $request->input('follow_up_at') : null,
        ]);
        $validated = $request->validate([
            'applicant_id' => ['required', 'exists:applicants,id'],
            'interviewer_id' => ['nullable', 'exists:users,id'],
            'interview_type' => ['required', Rule::in(['video', 'in-person', 'phone'])],
            'scheduled_at' => ['required', 'date'],
            'status' => ['required', Rule::in(['scheduled', 'completed', 'cancelled'])],
            'feedback' => ['nullable', 'string'],
            'follow_up_at' => ['nullable', 'date'],
            'follow_up_notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $validated['follow_up_at'] = ! empty($validated['follow_up_at']) ? $validated['follow_up_at'] : null;

        $interview->update($validated);

        return redirect()->route('interviews.index')->with('success', 'Interview updated successfully.');
    }

    public function destroy(Interview $interview)
    {
        $interview->delete();

        return redirect()->route('interviews.index')->with('success', 'Interview deleted successfully.');
    }

    private function interviewers()
    {
        $currentUser = Auth::user();
        $users = User::query()->forActiveDirectory();

        if ($currentUser?->company_id) {
            $users->where('company_id', $currentUser->company_id);
        }

        return $users->orderBy('name')->get();
    }
}
