<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class SubmissionCheckModel extends Model
{
    public function all(): array
    {
        return $this->db->query("
            SELECT sc.*, s.submission_no, s.title, c.title_en, c.title_ar
            FROM submission_checks sc
            INNER JOIN submissions s ON s.id = sc.submission_id
            INNER JOIN conferences c ON c.id = s.conference_id
            ORDER BY sc.id DESC
        ")->fetchAll();
    }

    public function findBySubmission(int $submissionId): ?array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM submission_checks
            WHERE submission_id = :submission_id
            LIMIT 1
        ");
        $stmt->execute([':submission_id' => $submissionId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function save(int $submissionId, array $data): void
    {
        $stmt = $this->db->prepare("
            INSERT INTO submission_checks (
                submission_id, plagiarism_score, plagiarism_notes,
                format_check_status, format_notes, checklist_json, checked_by, checked_at
            ) VALUES (
                :submission_id, :plagiarism_score, :plagiarism_notes,
                :format_check_status, :format_notes, :checklist_json, :checked_by, NOW()
            )
            ON DUPLICATE KEY UPDATE
                plagiarism_score = VALUES(plagiarism_score),
                plagiarism_notes = VALUES(plagiarism_notes),
                format_check_status = VALUES(format_check_status),
                format_notes = VALUES(format_notes),
                checklist_json = VALUES(checklist_json),
                checked_by = VALUES(checked_by),
                checked_at = NOW()
        ");
        $stmt->execute([
            ':submission_id' => $submissionId,
            ':plagiarism_score' => $data['plagiarism_score'] !== '' ? $data['plagiarism_score'] : null,
            ':plagiarism_notes' => $data['plagiarism_notes'] ?: null,
            ':format_check_status' => $data['format_check_status'] ?: 'pending',
            ':format_notes' => $data['format_notes'] ?: null,
            ':checklist_json' => $data['checklist_json'] ?: null,
            ':checked_by' => $data['checked_by'] ?: null,
        ]);
    }
}
