<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class PbgTaskPayment extends Model
{
    protected $fillable = [
        'pbg_task_id',
        'pbg_task_uid',
        'registration_number',
        'sts_form_number',
        'payment_date',
        'pad_amount'
    ];

    protected $casts = [
        'payment_date' => 'date',
        'pad_amount' => 'decimal:2'
    ];

    /**
     * Get the PBG task that owns this payment
     */
    public function pbgTask(): BelongsTo
    {
        return $this->belongsTo(PbgTask::class, 'pbg_task_id', 'id');
    }

    /**
     * Clean and convert registration number for matching
     */
    public static function cleanRegistrationNumber(string $registrationNumber): string
    {
        return trim($registrationNumber);
    }

    /**
     * Convert pad amount string to decimal
     */
    public static function convertPadAmount(?string $padAmount): float
    {
        if (empty($padAmount)) {
            return 0.0;
        }

        // Remove dots (thousands separator) and convert to float
        $cleaned = str_replace('.', '', $padAmount);
        $cleaned = str_replace(',', '.', $cleaned); // Handle comma as decimal separator if present
        
        return is_numeric($cleaned) ? (float) $cleaned : 0.0;
    }

    /**
     * Convert date string to proper format
     */
    public static function convertPaymentDate(?string $dateString): ?string
    {
        if (empty($dateString)) {
            return null;
        }

        try {
            return Carbon::parse($dateString)->format('Y-m-d');
        } catch (\Exception $e) {
            return null;
        }
    }
}
