<?php
/**
 * Created by PhpStorm.
 * User: Pritom
 * Date: 5/16/2024
 * Time: 12:00 AM
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use Flyerimage\Core\Database\MigrationBase;

return new class extends MigrationBase  {
    public function up() {
        $this->table = \Flyerimage\App\Constants\ITables::$FLYER_TEMPLATES;
        $this->columns = [
            "`id` bigint NOT NULL AUTO_INCREMENT",
            "`template_name` LONGTEXT",
            "`template_description` LONGTEXT",
            "`template_data` LONGTEXT",
            "`template_created_at` DATE NOT NULL",
            "PRIMARY KEY (`id`)",
        ];

        for ($template_id = 1; $template_id <= 10; $template_id++) {
            $from_path = FLYER_IMAGE_PUBLIC_PATH . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, ["static", "images", "template{$template_id}"]);
            if (file_exists($from_path)) {
                $template_text = $from_path . DIRECTORY_SEPARATOR . "template.txt";
                if (file_exists($template_text)) {
                    $template_text = file_get_contents($template_text);
                    $json = json_decode($template_text);

                    $tableName = $this->table_name($this->table);
                    $escapedName   = addslashes($json->title);
                    $escapedData   = addslashes($template_text);    // Note: $template_text is a file path string
                    $currentDate   = date('Y-m-d');

                    $rawQuery = "INSERT INTO `{$tableName}` (`template_name`, `template_description`, `template_data`, `template_created_at`) 
             VALUES ('{$escapedName}', '', '{$escapedData}', '{$currentDate}')";

                    $this->queries[] = $rawQuery;
                }
            }
        }
    }

    public function down() {
        $this->table = \Flyerimage\App\Constants\ITables::$FLYER_TEMPLATES;
        $this->queries[] = "DROP TABLE IF EXISTS {$this->table_name($this->table)}";
    }
};