<?php

namespace App\Models;

use App\Entities\JobApplication;
use CodeIgniter\Model;

class JobApplicationModel extends Model
{
    protected $table         = 'job_applications';
    protected $primaryKey    = 'id';
    protected $returnType    = JobApplication::class;
    protected $useTimestamps = true;
    protected $createdField  = 'applied_at';
    protected $allowedFields = [
        'job_id', 'candidate_profile_id', 'resume_id', 'cover_note',
        'status', 'assigned_recruiter_id',
    ];

    public function alreadyApplied(int $jobId, int $candidateProfileId): bool
    {
        return $this->where('job_id', $jobId)->where('candidate_profile_id', $candidateProfileId)->first() !== null;
    }

    public function forJob(int $jobId, ?string $status = null, int $page = 1, int $perPage = 20): array
    {
        $builder = $this->where('job_id', $jobId);
        if ($status) {
            $builder->where('status', $status);
        }
        $offset = ($page - 1) * $perPage;
        return $builder->orderBy('applied_at', 'DESC')->findAll($perPage, $offset);
    }

    public function forCandidate(int $candidateProfileId): array
    {
        return $this->select('job_applications.*, jobs.title as job_title, jobs.seo_slug as job_slug')
            ->join('jobs', 'jobs.id = job_applications.job_id')
            ->where('candidate_profile_id', $candidateProfileId)
            ->orderBy('applied_at', 'DESC')
            ->asArray()
            ->findAll();
    }

    /**
     * ATS Kanban view — grouped by status for a given job (or all of an
     * agency's jobs when $jobId is null), joined with candidate basics.
     */
    public function kanbanFor(int $agencyId, ?int $jobId = null): array
    {
        $builder = $this->db->table('job_applications ja')
            ->select('ja.*, cp.id as cp_id, u.name as candidate_name, j.title as job_title')
            ->join('jobs j', 'j.id = ja.job_id')
            ->join('candidate_profiles cp', 'cp.id = ja.candidate_profile_id')
            ->join('users u', 'u.id = cp.user_id')
            ->where('j.agency_id', $agencyId);

        if ($jobId) {
            $builder->where('ja.job_id', $jobId);
        }

        $rows = $builder->orderBy('ja.applied_at', 'DESC')->get()->getResultArray();

        $grouped = [
            'applied' => [], 'under_review' => [], 'shortlisted' => [],
            'interview_scheduled' => [], 'interview_completed' => [], 'rejected' => [], 'hired' => [],
        ];
        foreach ($rows as $row) {
            $grouped[$row['status']][] = $row;
        }
        return $grouped;
    }
}
