<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class DecisionModel extends Model
{
    public function getBySubmission(int $submissionId): ?array
    {
        $stmt = $this->db->prepare("
            SELECT d.*, u.first_name, u.last_name
            FROM decisions d
            INNER JOIN users u ON u.id = d.decided_by
            WHERE d.submission_id = :submission_id
            LIMIT 1
        ");
        $stmt->execute([':submission_id' => $submissionId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function historyBySubmission(int $submissionId): array
    {
        $stmt = $this->db->prepare("
            SELECT dh.*, u.first_name, u.last_name
            FROM decision_history dh
            INNER JOIN users u ON u.id = dh.decided_by
            WHERE dh.submission_id = :submission_id
            ORDER BY dh.id DESC
        ");
        $stmt->execute([':submission_id' => $submissionId]);
        return $stmt->fetchAll();
    }

    public function saveDecision(array $data): int
    {
        $existing = $this->getBySubmission((int) $data['submission_id']);

        if ($existing) {
            $stmt = $this->db->prepare("
                UPDATE decisions SET
                    decided_by = :decided_by,
                    decision = :decision,
                    chair_comments = :chair_comments,
                    decided_at = NOW(),
                    notification_sent = 0
                WHERE submission_id = :submission_id
            ");
            $stmt->execute([
                ':submission_id' => $data['submission_id'],
                ':decided_by' => $data['decided_by'],
                ':decision' => $data['decision'],
                ':chair_comments' => $data['chair_comments'] ?: null,
            ]);
            $decisionId = (int) $existing['id'];
        } else {
            $stmt = $this->db->prepare("
                INSERT INTO decisions (
                    submission_id, decided_by, decision, chair_comments, decided_at, notification_sent
                ) VALUES (
                    :submission_id, :decided_by, :decision, :chair_comments, NOW(), 0
                )
            ");
            $stmt->execute([
                ':submission_id' => $data['submission_id'],
                ':decided_by' => $data['decided_by'],
                ':decision' => $data['decision'],
                ':chair_comments' => $data['chair_comments'] ?: null,
            ]);
            $decisionId = (int) $this->db->lastInsertId();
        }

        $hist = $this->db->prepare("
            INSERT INTO decision_history (
                submission_id, decision, chair_comments, decided_by
            ) VALUES (
                :submission_id, :decision, :chair_comments, :decided_by
            )
        ");
        $hist->execute([
            ':submission_id' => $data['submission_id'],
            ':decision' => $data['decision'],
            ':chair_comments' => $data['chair_comments'] ?: null,
            ':decided_by' => $data['decided_by'],
        ]);

        return $decisionId;
    }

    public function aggregateReviewStats(int $submissionId): array
    {
        $stmt = $this->db->prepare("
            SELECT
                COUNT(r.id) AS reviews_count,
                AVG(r.overall_score) AS average_score
            FROM review_assignments ra
            LEFT JOIN reviews r ON r.review_assignment_id = ra.id
            WHERE ra.submission_id = :submission_id
              AND ra.status = 'completed'
        ");
        $stmt->execute([':submission_id' => $submissionId]);
        $row = $stmt->fetch() ?: [];
        return [
            'reviews_count' => (int) ($row['reviews_count'] ?? 0),
            'average_score' => $row['average_score'] !== null ? round((float) $row['average_score'], 2) : null,
        ];
    }
}
