<?php

namespace App\Services\Payments;

use App\Models\Configuration;
use App\Models\Payment;
use Illuminate\Support\Facades\Schema;

class PaymentPlanService
{
    public function createPlan(array $payload): Payment
    {
        $schoolYear = $payload['school_year'] ?? Configuration::getConfig('school_year');
        $semester = $payload['semester'] ?? Configuration::getConfig('semester');

        $data = [
            'parent_id' => (int) $payload['parent_id'],
            'total_amount' => (float) $payload['total_amount'],
            'number_of_installments' => (int) $payload['number_of_installments'],
            'paid_amount' => 0,
            'balance' => (float) $payload['total_amount'],
            'payment_date' => $payload['payment_date'] ?? null,
            'payment_method' => $payload['payment_method'] ?? null,
            'status' => $payload['status'] ?? 'Pending',
            'semester' => $semester,
            'school_year' => $schoolYear,
        ];

        if (isset($payload['invoice_id']) && Schema::hasColumn('payments', 'invoice_id')) {
            $data['invoice_id'] = (int) $payload['invoice_id'];
        }

        if (isset($payload['payment_type']) && Schema::hasColumn('payments', 'payment_type')) {
            $data['payment_type'] = $payload['payment_type'];
        }

        return Payment::query()->create($data);
    }
}
