<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        DB::unprepared('
            CREATE TRIGGER update_totals_before_quantity_change
            BEFORE UPDATE ON warehouse_stocks
            FOR EACH ROW
            BEGIN
                -- Check if the quantity has changed
                IF NEW.quantity != OLD.quantity THEN
                    -- Update tp_price_total and mrp_price_total based on the new quantity
                    SET NEW.tp_price_total = NEW.tp_price * NEW.quantity;
                    SET NEW.mrp_price_total = NEW.mrp_price * NEW.quantity;
                    SET NEW.unit_price_total = NEW.unit_price * NEW.quantity;
                END IF;
            END
        ');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::unprepared('DROP TRIGGER IF EXISTS update_totals_before_quantity_change');
    }
};
