<?php

declare(strict_types=1);

class ResultPublishService
{
    private PDO $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * Unified method to update the publication status of results.
     */
    public function updateStatus(
        int $school_id,
        int $session_id,
        int $exam_type_id,
        int $class_id,
        bool $publish
    ): bool {
        $stmt = $this->pdo->prepare("
            UPDATE exam_results
            SET 
                is_published = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE school_id = ?
            AND session_id = ?
            AND exam_type_id = ?
            AND class_id = ?
        ");

        return $stmt->execute([
            $publish ? 1 : 0,
            $school_id,
            $session_id,
            $exam_type_id,
            $class_id
        ]);
    }

    /**
     * Verifies if any results exist for the criteria.
     */
    public function countResults(
        int $school_id,
        int $session_id,
        int $exam_type_id,
        int $class_id
    ): int {
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) 
            FROM exam_results 
            WHERE school_id = ? 
            AND session_id = ? 
            AND exam_type_id = ? 
            AND class_id = ?
        ");
        
        $stmt->execute([$school_id, $session_id, $exam_type_id, $class_id]);
        return (int) $stmt->fetchColumn();
    }

    /**
     * Checks if results are currently published.
     */
    public function isPublished(
        int $school_id,
        int $session_id,
        int $exam_type_id,
        int $class_id
    ): bool {
        $stmt = $this->pdo->prepare("
            SELECT COUNT(*) 
            FROM exam_results 
            WHERE school_id = ? 
            AND session_id = ? 
            AND exam_type_id = ? 
            AND class_id = ? 
            AND is_published = 1
        ");

        $stmt->execute([$school_id, $session_id, $exam_type_id, $class_id]);
        return (int) $stmt->fetchColumn() > 0;
    }
}