<?php

use App\Database\Migration;

/**
 * Migration 010 – Event Module (Phase 4b)
 *
 * Creates:
 *   iw_event_categories  – event categories
 *   iw_events            – events with dual-status, media_id FK, featured flag
 */
class CreateEventTables extends Migration
{
    public function up(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_event_categories (
                id          INT          AUTO_INCREMENT PRIMARY KEY,
                name        VARCHAR(100) NOT NULL,
                slug        VARCHAR(100) NOT NULL UNIQUE,
                description TEXT         DEFAULT NULL,
                sort_order  INT          NOT NULL DEFAULT 0
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_events (
                id             INT           AUTO_INCREMENT PRIMARY KEY,
                title          VARCHAR(255)  NOT NULL,
                slug           VARCHAR(255)  NOT NULL UNIQUE,
                excerpt        TEXT          DEFAULT NULL,
                content        LONGTEXT      DEFAULT NULL,
                location       VARCHAR(255)  DEFAULT NULL,
                start_date     DATE          NOT NULL,
                start_time     TIME          DEFAULT NULL,
                end_date       DATE          DEFAULT NULL,
                end_time       TIME          DEFAULT NULL,
                media_id       INT           DEFAULT NULL,
                category_id    INT           DEFAULT NULL,
                is_featured    TINYINT(1)    NOT NULL DEFAULT 0,
                publish_status ENUM('draft','published') NOT NULL DEFAULT 'draft',
                event_status   ENUM('scheduled','postponed','cancelled') NOT NULL DEFAULT 'scheduled',
                created_by     INT           DEFAULT NULL,
                created_at     DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at     DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

                INDEX idx_start_date    (start_date),
                INDEX idx_publish_status (publish_status),
                INDEX idx_event_status  (event_status),
                INDEX idx_featured      (is_featured),
                INDEX idx_category      (category_id),
                INDEX idx_media         (media_id),

                FOREIGN KEY (category_id) REFERENCES iw_event_categories(id) ON DELETE SET NULL,
                FOREIGN KEY (media_id)    REFERENCES iw_media(id)            ON DELETE SET NULL,
                FOREIGN KEY (created_by)  REFERENCES iw_users(id)            ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_events");
        $this->db->query("DROP TABLE IF EXISTS iw_event_categories");
    }
}
