<?php

namespace Database\Seeders;

use App\Models\AppSetting;
use App\Models\Invoice;
use App\Models\Location;
use App\Models\Payment;
use App\Models\PaymentAllocation;
use App\Models\Tenant;
use App\Models\Unit;
use App\Models\Lease;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

use Illuminate\Support\Facades\DB;


class RukoBerkahUmiSeeder extends Seeder
{
    public function run(): void
    {
      /*
      |--------------------------------------------------------------------------
      | RESET DATA (aman untuk DEV)
      |--------------------------------------------------------------------------
      */
      DB::statement('SET FOREIGN_KEY_CHECKS=0;');

      DB::table('payment_allocations')->truncate();
      DB::table('payments')->truncate();
      DB::table('invoice_items')->truncate();
      DB::table('invoices')->truncate();
      DB::table('leases')->truncate();
      DB::table('units')->truncate();
      DB::table('tenants')->truncate();
      DB::table('locations')->truncate();
      // app_settings jangan di-truncate kalau kamu mau tetap 1 record, tapi boleh juga:
      DB::table('app_settings')->truncate();

      DB::statement('SET FOREIGN_KEY_CHECKS=1;');


        /*
        |--------------------------------------------------------------------------
        | APP SETTINGS
        |--------------------------------------------------------------------------
        */
        AppSetting::updateOrCreate(
            ['id' => 1],
            [
                'wa_enabled' => true,
                'wa_phone_admin' => '6281234567890',
                'wa_sender_label' => 'Admin Ruko BERKAH UMI',
                'wa_message_template' => "Halo {tenant_name},\n\nKami informasikan pembayaran sewa Anda:\nNo: {receipt_no}\nTotal: Rp{amount}\n\nKuitansi:\n{public_url}\n\nTerima kasih.",
                'public_receipt_enabled' => true,
                'public_receipt_expiry_days' => 365,
                'receipt_brand_name' => 'Ruko BERKAH UMI',
                'receipt_footer_note' => 'Terima kasih atas kepercayaan Anda.',
            ]
        );

        /*
        |--------------------------------------------------------------------------
        | LOCATIONS
        |--------------------------------------------------------------------------
        */
        $lokasiA = Location::create([
            'name' => 'Komplek Ruko Utama',
            'code' => 'KRU',
            'is_active' => true,
        ]);

        $lokasiB = Location::create([
            'name' => 'Komplek Ruko Selatan',
            'code' => 'KRS',
            'is_active' => true,
        ]);

        /*
        |--------------------------------------------------------------------------
        | UNITS (10 ruko)
        |--------------------------------------------------------------------------
        */
        $units = collect();

        for ($i = 1; $i <= 6; $i++) {
            $units->push(Unit::create([
                'location_id' => $lokasiA->id,
                'code' => 'A-' . str_pad($i, 2, '0', STR_PAD_LEFT),
                'name' => "Ruko A{$i}",
                'default_monthly_price' => 1500000 + ($i * 100000),
                'default_due_day' => 10,
                'is_active' => true,
            ]));
        }

        for ($i = 1; $i <= 4; $i++) {
            $units->push(Unit::create([
                'location_id' => $lokasiB->id,
                'code' => 'B-' . str_pad($i, 2, '0', STR_PAD_LEFT),
                'name' => "Ruko B{$i}",
                'default_monthly_price' => 2000000,
                'default_due_day' => 15,
                'is_active' => true,
            ]));
        }

        /*
        |--------------------------------------------------------------------------
        | TENANTS
        |--------------------------------------------------------------------------
        */
        $andi = Tenant::create([
            'name' => 'Andi Wijaya',
            'phone' => '0811111111',
            'is_active' => true,
        ]);

        $budi = Tenant::create([
            'name' => 'Budi Santoso',
            'phone' => '0822222222',
            'is_active' => true,
        ]);

        $citra = Tenant::create([
            'name' => 'Citra Mandiri',
            'phone' => '0833333333',
            'is_active' => true,
        ]);

        /*
        |--------------------------------------------------------------------------
        | LEASES (BERBAGAI KONDISI)
        |--------------------------------------------------------------------------
        */

        // 1️⃣ ANDI – 2 ruko – BULANAN (1 invoice)
        Lease::create([
            'unit_id' => $units[0]->id,
            'tenant_id' => $andi->id,
            'billing_cycle' => 'monthly',
            'start_date' => now()->subMonths(2)->startOfMonth(),
            'price_amount' => 1600000,
            'due_day' => 10,
            'prorate_enabled' => true,
            'status' => 'active',
        ]);

        Lease::create([
            'unit_id' => $units[1]->id,
            'tenant_id' => $andi->id,
            'billing_cycle' => 'monthly',
            'start_date' => now()->subMonths(2)->startOfMonth(),
            'price_amount' => 1700000,
            'due_day' => 10,
            'prorate_enabled' => true,
            'status' => 'active',
        ]);

        // 2️⃣ BUDI – 1 ruko – TAHUNAN (Agustus–Juli)
        Lease::create([
            'unit_id' => $units[2]->id,
            'tenant_id' => $budi->id,
            'billing_cycle' => 'yearly',
            'start_date' => Carbon::create(now()->year, 8, 1),
            'price_amount' => 18000000,
            'yearly_anchor_month' => 8,
            'prorate_enabled' => false,
            'status' => 'active',
        ]);

        // 3️⃣ CITRA – PRORATE (masuk tengah bulan)
        Lease::create([
            'unit_id' => $units[3]->id,
            'tenant_id' => $citra->id,
            'billing_cycle' => 'monthly',
            'start_date' => now()->startOfMonth()->addDays(10),
            'price_amount' => 1900000,
            'due_day' => 15,
            'prorate_enabled' => true,
            'status' => 'active',
        ]);

        // 4️⃣ RUKO KOSONG (units[4], units[5], units[6] dst)
        // sengaja tidak dibuat lease

        /*
        |--------------------------------------------------------------------------
        | GENERATE INVOICE
        |--------------------------------------------------------------------------
        */
        $this->command->info('➡ Generating invoices...');
        app(\App\Domain\Rent\Services\InvoiceGeneratorService::class)
            ->generateForDate(now());

        /*
        |--------------------------------------------------------------------------
        | PAYMENTS (PAID & PARTIAL)
        |--------------------------------------------------------------------------
        */
        $invoiceAndi = Invoice::where('tenant_id', $andi->id)->latest()->first();
        $invoiceBudi = Invoice::where('tenant_id', $budi->id)->latest()->first();

        // ✅ ANDI – LUNAS
        $payAndi = Payment::create([
            'tenant_id' => $andi->id,
            'paid_at' => now(),
            'method' => 'transfer',
            'total_amount' => $invoiceAndi->total_amount,
            'receipt_no' => 'RCPT-' . now()->format('Y') . '-000001',
            'public_token' => Str::random(40),
        ]);

        PaymentAllocation::create([
            'payment_id' => $payAndi->id,
            'invoice_id' => $invoiceAndi->id,
            'amount_applied' => $invoiceAndi->total_amount,
        ]);

        $invoiceAndi->recalcTotals();
        $invoiceAndi->save();

        // ⚠️ BUDI – CICIL (PARTIAL)
        $payBudi = Payment::create([
            'tenant_id' => $budi->id,
            'paid_at' => now(),
            'method' => 'cash',
            'total_amount' => 5000000,
            'receipt_no' => 'RCPT-' . now()->format('Y') . '-000002',
            'public_token' => Str::random(40),
        ]);

        PaymentAllocation::create([
            'payment_id' => $payBudi->id,
            'invoice_id' => $invoiceBudi->id,
            'amount_applied' => 5000000,
        ]);

        $invoiceBudi->recalcTotals();
        $invoiceBudi->save();

        $this->command->info('✅ Seeder Ruko BERKAH UMI selesai.');
    }
}
