<?php

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

/**
 * Distinguish *why* a cash movement exists, independently of its direction.
 *
 * `type` only says which way the money went, so telling an automatic sale
 * take-in apart from a manual float top-up previously meant string-matching
 * the free-text note ("Sale %") — which quietly miscounts the moment a cashier
 * writes a note that happens to start the same way. Shift reconciliation needs
 * "cash from sales" and "cash paid in by hand" as separate lines, so the
 * distinction is recorded explicitly.
 *
 * Backfill uses the same note prefixes the old reporting relied on, so history
 * keeps the classification it already had.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('cash_movements', function (Blueprint $table) {
            $table->enum('source', ['sale', 'refund', 'manual'])->default('manual')->after('type')->index();
        });

        DB::table('cash_movements')->where('type', 'cash_refund')->update(['source' => 'refund']);
        DB::table('cash_movements')->where('type', 'in')->where('note', 'like', 'Sale %')->update(['source' => 'sale']);
        DB::table('cash_movements')->where('type', 'in')->where('note', 'like', 'Amended sale %')->update(['source' => 'sale']);
    }

    public function down(): void
    {
        Schema::table('cash_movements', function (Blueprint $table) {
            $table->dropColumn('source');
        });
    }
};
