<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class ProceedingsBookModel extends Model
{
    public function getByConference(int $conferenceId): ?array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM proceedings_books
            WHERE conference_id = :conference_id
            LIMIT 1
        ");
        $stmt->execute([':conference_id' => $conferenceId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function save(int $conferenceId, array $data): void
    {
        $stmt = $this->db->prepare("
            INSERT INTO proceedings_books (
                conference_id, title_en, title_ar, isbn_print, isbn_online,
                editor_en, editor_ar, preface_en, preface_ar, cover_image, is_published
            ) VALUES (
                :conference_id, :title_en, :title_ar, :isbn_print, :isbn_online,
                :editor_en, :editor_ar, :preface_en, :preface_ar, :cover_image, :is_published
            )
            ON DUPLICATE KEY UPDATE
                title_en = VALUES(title_en),
                title_ar = VALUES(title_ar),
                isbn_print = VALUES(isbn_print),
                isbn_online = VALUES(isbn_online),
                editor_en = VALUES(editor_en),
                editor_ar = VALUES(editor_ar),
                preface_en = VALUES(preface_en),
                preface_ar = VALUES(preface_ar),
                cover_image = VALUES(cover_image),
                is_published = VALUES(is_published)
        ");
        $stmt->execute([
            ':conference_id' => $conferenceId,
            ':title_en' => $data['title_en'],
            ':title_ar' => $data['title_ar'] ?: null,
            ':isbn_print' => $data['isbn_print'] ?: null,
            ':isbn_online' => $data['isbn_online'] ?: null,
            ':editor_en' => $data['editor_en'] ?: null,
            ':editor_ar' => $data['editor_ar'] ?: null,
            ':preface_en' => $data['preface_en'] ?: null,
            ':preface_ar' => $data['preface_ar'] ?: null,
            ':cover_image' => $data['cover_image'] ?: null,
            ':is_published' => !empty($data['is_published']) ? 1 : 0,
        ]);
    }
}
