<?php

namespace Database\Seeders;

use App\Models\CustomerBalance;
use App\Models\Customer;
use App\Models\ReceiptVoucher;
use App\Models\PaymentVoucher;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CustomerBalanceSeeder extends Seeder
{
    public function run(): void
    {
        // حساب أرصدة العملاء بناءً على المعاملات الفعلية
        $customers = Customer::all();

        foreach ($customers as $customer) {
            // إجمالي المقبوضات (سندات القبض)
            $totalReceipts = DB::table('receipt_vouchers')
                ->where('customer_id', $customer->id)
                ->where('status', 'active')
                ->sum('amount');

            // إجمالي المردودات
            $totalRefunds = DB::table('receipt_vouchers')
                ->where('customer_id', $customer->id)
                ->where('status', 'refunded')
                ->sum('amount');

            // إجمالي المصروفات (سندات الصرف)
            $totalExpenses = DB::table('payment_vouchers')
                ->where('customer_id', $customer->id)
                ->where('status', 'active')
                ->sum('amount');

            // الرصيد الحالي = المقبوضات - (المردودات + المصروفات)
            $currentBalance = $totalReceipts - ($totalRefunds + $totalExpenses);

            // آخر معاملة
            $lastReceipt = ReceiptVoucher::where('customer_id', $customer->id)
                ->where('status', 'active')
                ->orderBy('payment_date', 'desc')
                ->first();

            $lastPayment = PaymentVoucher::where('customer_id', $customer->id)
                ->where('status', 'active')
                ->orderBy('payment_date', 'desc')
                ->first();

            $lastTransaction = null;
            $lastTransactionType = null;
            $lastTransactionAmount = null;

            if ($lastReceipt && $lastPayment) {
                if ($lastReceipt->payment_date > $lastPayment->payment_date) {
                    $lastTransaction = $lastReceipt->payment_date;
                    $lastTransactionType = $lastReceipt->type == 'subscription' ? 'payment' : 'adjustment';
                    $lastTransactionAmount = $lastReceipt->amount;
                } else {
                    $lastTransaction = $lastPayment->payment_date;
                    $lastTransactionType = 'expense';
                    $lastTransactionAmount = $lastPayment->amount;
                }
            } elseif ($lastReceipt) {
                $lastTransaction = $lastReceipt->payment_date;
                $lastTransactionType = $lastReceipt->type == 'subscription' ? 'payment' : 'adjustment';
                $lastTransactionAmount = $lastReceipt->amount;
            } elseif ($lastPayment) {
                $lastTransaction = $lastPayment->payment_date;
                $lastTransactionType = 'expense';
                $lastTransactionAmount = $lastPayment->amount;
            }

            CustomerBalance::create([
                'customer_id' => $customer->id,
                'current_balance' => $currentBalance,
                'total_paid' => $totalReceipts,
                'total_refunded' => $totalRefunds,
                'last_transaction_date' => $lastTransaction,
                'last_transaction_type' => $lastTransactionType,
                'last_transaction_amount' => $lastTransactionAmount,
                'notes' => 'تم تحديث الرصيد تلقائياً',
            ]);
        }
    }
}
