<?php

require __DIR__ . '/../app/Core/Database.php';

use App\Core\Database;

$config = require __DIR__ . '/../config/templates/ltv26_scoresheet.php';
$image = $config['image'];
$width = $config['width'];
$height = $config['height'];
unset($config['image'], $config['width'], $config['height']);

$db = Database::connection();
$stmt = $db->prepare(
    'INSERT INTO sheet_templates (code, name, image_path, page_width, page_height, config_json, active)
     VALUES ("ltv26", "Planilla LTV 26", :image_path, :page_width, :page_height, :config_json, 1)
     ON DUPLICATE KEY UPDATE image_path = VALUES(image_path), page_width = VALUES(page_width), page_height = VALUES(page_height), config_json = VALUES(config_json), active = 1'
);
$stmt->execute([
    'image_path' => $image,
    'page_width' => $width,
    'page_height' => $height,
    'config_json' => json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
]);

$templateId = (int) $db->lastInsertId();
if ($templateId === 0) {
    $templateId = (int) $db->query('SELECT id FROM sheet_templates WHERE code = "ltv26"')->fetch()['id'];
}

$tournaments = $db->query('SELECT id FROM tournaments')->fetchAll();
foreach ($tournaments as $tournament) {
    $db->prepare(
        'INSERT IGNORE INTO tournament_sheet_templates (tournament_id, sheet_template_id, is_default)
         VALUES (:tournament_id, :sheet_template_id, 1)'
    )->execute(['tournament_id' => $tournament['id'], 'sheet_template_id' => $templateId]);
}

echo "Plantilla LTV26 registrada con ID $templateId\n";
