<?php

namespace App\Models;

use CodeIgniter\Model;

class ReferenceModel extends Model
{
    protected $table         = 'references';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'document_id', 'reference_type', 'cited_document_id',
        'title', 'author', 'journal', 'year', 'volume', 'issue',
        'pages', 'doi', 'url', 'raw_text', 'sort_order',
    ];

    public function getForDocument(int $document_id): array
    {
        return $this->db->table('references r')
            ->select('r.*, d.title AS cited_title, d.author_name AS cited_author, d.year AS cited_year, dt.name AS cited_type')
            ->join('documents d', 'd.id = r.cited_document_id', 'left')
            ->join('document_types dt', 'dt.id = d.document_type_id', 'left')
            ->where('r.document_id', $document_id)
            ->orderBy('r.sort_order', 'ASC')
            ->orderBy('r.id', 'ASC')
            ->get()->getResultArray();
    }

    public function deleteForDocument(int $document_id): void
    {
        $this->where('document_id', $document_id)->delete();
    }

    /**
     * Save/replace all references for a document from POST data.
     * Expects array of reference arrays.
     */
    public function saveForDocument(int $document_id, array $refs): void
    {
        $this->deleteForDocument($document_id);

        $now = date('Y-m-d H:i:s');
        foreach ($refs as $i => $ref) {
            $type = $ref['reference_type'] ?? 'external';

            $this->insert([
                'document_id'       => $document_id,
                'reference_type'    => $type,
                'cited_document_id' => $type === 'internal' ? ($ref['cited_document_id'] ?? null) : null,
                'title'             => isset($ref['title']) ? substr(trim($ref['title']), 0, 500) : null,
                'author'            => isset($ref['author']) ? substr(trim($ref['author']), 0, 255) : null,
                'journal'           => isset($ref['journal']) ? substr(trim($ref['journal']), 0, 255) : null,
                'year'              => !empty($ref['year']) ? (int) $ref['year'] : null,
                'volume'            => $ref['volume'] ?? null,
                'issue'             => $ref['issue'] ?? null,
                'pages'             => $ref['pages'] ?? null,
                'doi'               => $ref['doi'] ?? null,
                'url'               => $ref['url'] ?? null,
                'raw_text'          => $ref['raw_text'] ?? null,
                'sort_order'        => $i,
                'created_at'        => $now,
                'updated_at'        => $now,
            ]);
        }
    }
}
