<?php
namespace App\Services;

class CertificateService {
    public function __construct(private \PDO $pdo) {}

    public function issue(int $studentId, int $courseId, ?float $finalMark, int $issuedBy): int {
        $stmt = $this->pdo->prepare("SELECT s.student_number, u.first_name, u.last_name, c.title FROM students s JOIN users u ON s.user_id = u.id JOIN courses c ON c.id = ? WHERE s.id = ?");
        $stmt->execute([$courseId, $studentId]);
        $row = $stmt->fetch();
        if (!$row) return 0;
        $number = generate_certificate_number($this->pdo);
        $this->pdo->prepare("INSERT INTO certificates (certificate_number, student_id, course_id, student_name, course_name, issue_date, final_mark, status, issued_by) VALUES (?, ?, ?, ?, ?, CURDATE(), ?, 'issued', ?)")
            ->execute([$number, $studentId, $courseId, trim($row['first_name'] . ' ' . $row['last_name']), $row['title'], $finalMark, $issuedBy]);
        return (int)$this->pdo->lastInsertId();
    }
}
