
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_delete`');
        DB::unprepared('CREATE TRIGGER `item_stock_delete` AFTER DELETE ON `items_sizes`
             FOR EACH ROW BEGIN
                UPDATE `items` SET `stock` = ( SELECT SUM(`stock`) FROM `items_sizes` WHERE `item_id` = OLD.`item_id` ) WHERE `id` = OLD.`item_id`;
            END');
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_insert`');
        DB::unprepared('CREATE TRIGGER `item_stock_insert` AFTER INSERT ON `items_sizes`
             FOR EACH ROW BEGIN
                UPDATE `items` SET `stock` = ( SELECT SUM(`stock`) FROM `items_sizes` WHERE `item_id` = NEW.`item_id` ) WHERE `id` = NEW.`item_id`;
            END');
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_update`');
        DB::unprepared('CREATE TRIGGER `item_stock_update` AFTER UPDATE ON `items_sizes`
             FOR EACH ROW BEGIN
                UPDATE `items` SET `stock` = ( SELECT SUM(`stock`) FROM `items_sizes` WHERE `item_id` = NEW.`item_id` ) WHERE `id` = NEW.`item_id`;
            END');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_delete`');
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_insert`');
        DB::unprepared('DROP TRIGGER IF EXISTS `item_stock_update`');
    }
};
