<?php

use yii\db\Schema;
use yii\db\Migration;

class m181227_215706_fix_trigger_event_seat_count_check extends Migration
{
    public function up()
    {
        $this->execute("DROP TRIGGER IF EXISTS event_seat_count_check;");
        $this->execute("CREATE TRIGGER event_seat_count_check
                 AFTER INSERT ON event_registration FOR EACH ROW
                 BEGIN
                      IF (SELECT coalesce(COUNT(id),0) FROM event_registration
                           WHERE canceled_at is null AND id_event = NEW.id_event) 
                           >
                           (SELECT coalesce(seat_count,0) from event where id = NEW.id_event)
                      THEN
                           SIGNAL SQLSTATE '45000'
                                SET MESSAGE_TEXT = 'MAX_SEAT_COUNT_EXCEEDED';
                      END IF;
                 END;
        ");
    }

    public function down()
    {
        echo "m181227_215706_fix_trigger_event_seat_count_check cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}
