<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Expense Categories
        Schema::create('expense_categories', function (Blueprint $table) {
            $table->id();
            $table->string('name_ar');
            $table->string('name_en');
            $table->enum('type', ['vehicle', 'contract', 'general'])->default('general');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // 2. Expenses Table
        Schema::create('expenses', function (Blueprint $table) {
            $table->id();
            $table->date('expense_date');
            $table->foreignId('category_id')->constrained('expense_categories')->onDelete('cascade');
            $table->decimal('amount', 15, 2);
            $table->enum('payment_method', ['cash', 'card', 'transfer', 'mada', 'visa', 'stcpay']);
            $table->foreignId('car_id')->nullable()->constrained('cars')->onDelete('set null');
            $table->foreignId('rental_id')->nullable()->constrained('rentals')->onDelete('set null');
            $table->text('description')->nullable();
            $table->string('attachment')->nullable(); // Invoice photo
            $table->foreignId('created_by')->constrained('users')->onDelete('cascade');
            $table->enum('status', ['active', 'cancelled'])->default('active');
            $table->text('cancellation_reason')->nullable();
            $table->timestamps();
        });

        // 3. Payment Vouchers Table (سندات الصرف)
        Schema::create('payment_vouchers', function (Blueprint $table) {
            $table->id();
            $table->string('voucher_number')->unique();
            $table->date('voucher_date');
            $table->decimal('amount', 15, 2);
            $table->enum('payment_method', ['cash', 'card', 'transfer', 'mada', 'visa', 'stcpay']);
            $table->string('reason'); // Description of why the money is paid
            $table->foreignId('rental_id')->nullable()->constrained('rentals')->onDelete('set null');
            $table->foreignId('customer_id')->nullable()->constrained('customers')->onDelete('set null');
            $table->string('reference_type')->nullable(); // e.g. "insurance_refund"
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('created_by')->constrained('users')->onDelete('cascade');
            $table->enum('status', ['confirmed', 'cancelled'])->default('confirmed');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('payment_vouchers');
        Schema::dropIfExists('expenses');
        Schema::dropIfExists('expense_categories');
    }
};
