<?php

namespace App\Models;

use CodeIgniter\Model;

class InterviewModel extends Model
{
    protected $table         = 'interviews';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'job_application_id', 'scheduled_by_user_id', 'scheduled_at', 'duration_minutes',
        'mode', 'meeting_link', 'location', 'status', 'feedback', 'feedback_rating',
    ];

    public function forApplication(int $applicationId): array
    {
        return $this->where('job_application_id', $applicationId)->orderBy('scheduled_at', 'DESC')->findAll();
    }

    public function upcomingForCandidate(int $candidateUserId): array
    {
        return $this->select('interviews.*, ja.job_id, j.title as job_title')
            ->join('job_applications ja', 'ja.id = interviews.job_application_id')
            ->join('jobs j', 'j.id = ja.job_id')
            ->join('candidate_profiles cp', 'cp.id = ja.candidate_profile_id')
            ->where('cp.user_id', $candidateUserId)
            ->where('interviews.scheduled_at >=', date('Y-m-d H:i:s'))
            ->where('interviews.status', 'scheduled')
            ->orderBy('interviews.scheduled_at', 'ASC')
            ->findAll();
    }

    public function needingReminders(int $withinMinutes = 60): array
    {
        $windowEnd = date('Y-m-d H:i:s', strtotime("+{$withinMinutes} minutes"));
        return $this->where('status', 'scheduled')
            ->where('scheduled_at <=', $windowEnd)
            ->where('scheduled_at >=', date('Y-m-d H:i:s'))
            ->findAll();
    }
}
