<?php

namespace App\Models;

use CodeIgniter\Model;

class ResumeModel extends Model
{
    protected $table         = 'resumes';
    protected $allowedFields = ['candidate_profile_id', 'file_path', 'original_filename', 'is_primary', 'download_count', 'uploaded_at'];
    protected $validationRules = [
        'file_path'         => 'required',
        'original_filename' => 'required',
    ];

    public function forProfile(int $candidateProfileId): array
    {
        return $this->where('candidate_profile_id', $candidateProfileId)->orderBy('uploaded_at', 'DESC')->findAll();
    }

    public function primaryFor(int $candidateProfileId): ?array
    {
        return $this->where('candidate_profile_id', $candidateProfileId)->where('is_primary', 1)->first();
    }

    public function unsetOtherPrimaries(int $candidateProfileId, int $exceptResumeId): void
    {
        $this->where('candidate_profile_id', $candidateProfileId)
            ->where('id !=', $exceptResumeId)
            ->set('is_primary', 0)
            ->update();
    }

    public function incrementDownloadCount(int $resumeId): void
    {
        $this->set('download_count', 'download_count + 1', false)->where('id', $resumeId)->update();
    }
}
