<?php

namespace App\Models;

use CodeIgniter\Model;

class CitationModel extends Model
{
    protected $table         = 'citations';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;
    protected $allowedFields = ['citing_document_id', 'cited_document_id', 'created_at'];

    /**
     * Insert citation pairs for all internal references of a document.
     * Called on publish. Also increments citations_count on cited docs.
     */
    public function createFromDocument(int $citing_id): void
    {
        $refs = $this->db->table('references')
            ->where('document_id', $citing_id)
            ->where('reference_type', 'internal')
            ->whereNotNull('cited_document_id')
            ->get()->getResultArray();

        $docModel = model('DocumentModel');
        $now      = date('Y-m-d H:i:s');

        foreach ($refs as $ref) {
            $cited_id = (int) $ref['cited_document_id'];

            // Skip if already recorded (idempotent)
            $exists = $this->where('citing_document_id', $citing_id)
                ->where('cited_document_id', $cited_id)
                ->first();
            if ($exists) {
                continue;
            }

            $this->insert([
                'citing_document_id' => $citing_id,
                'cited_document_id'  => $cited_id,
                'created_at'         => $now,
            ]);

            $docModel->incrementCitations($cited_id);
        }
    }

    /**
     * Remove all citations for a document (on un-publish/delete).
     * Also decrements citations_count on affected cited docs.
     */
    public function removeFromDocument(int $citing_id): void
    {
        $existing = $this->where('citing_document_id', $citing_id)->findAll();
        $docModel = model('DocumentModel');

        foreach ($existing as $row) {
            $docModel->decrementCitations((int) $row['cited_document_id']);
        }

        $this->where('citing_document_id', $citing_id)->delete();
    }

    /** Who cited this document? Returns list of citing documents. */
    public function getCitedBy(int $cited_id): array
    {
        return $this->db->table('citations c')
            ->select('c.*, d.title, d.author_name, d.year, d.status')
            ->join('documents d', 'd.id = c.citing_document_id')
            ->where('c.cited_document_id', $cited_id)
            ->where('d.status', 'published')
            ->orderBy('d.year', 'DESC')
            ->get()->getResultArray();
    }
}
