<?php

namespace App\Filament\Resources\PointTransactionResource\Pages;

use App\Filament\Resources\PointTransactionResource;
use App\Models\ClientPoint;
use App\Models\PointTransaction;
use App\Settings\GeneralSettings;
use Filament\Resources\Pages\CreateRecord;

class CreatePointTransaction extends CreateRecord
{
    protected static string $resource = PointTransactionResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // الحصول على الرصيد الحالي
        $clientPoint = ClientPoint::firstOrCreate(
            ['client_id' => $data['client_id']],
            ['balance' => 0]
        );

        $data['balance_before'] = $clientPoint->balance;

        // تحديث الرصيد بناءً على نوع المعاملة
        if ($data['type'] === 'earned' || $data['type'] === 'admin_adjustment') {
            $clientPoint->balance += $data['points'];
            
            // حساب تاريخ الصلاحية للنقاط المكتسبة
            $settings = app(GeneralSettings::class);
            $expiryDays = $settings->points_expiry_days ?? 365;
            $data['expires_at'] = now()->addDays($expiryDays)->toDateString();
        } elseif ($data['type'] === 'spent' || $data['type'] === 'expired') {
            $clientPoint->balance -= abs($data['points']);
            // النقاط المستهلكة أو المنتهية لا تحتاج تاريخ صلاحية
            $data['expires_at'] = null;
        }

        $clientPoint->save();
        $data['balance_after'] = $clientPoint->balance;

        return $data;
    }
}





