<?php

namespace App\Filament\Resources\Contracts\Pages;

use App\Filament\Resources\Contracts\ContractResource;
use App\Models\PaymentTemplate;
use App\Models\PaymentSchedule;
use App\Models\PaymentScheduleItem;
use Filament\Resources\Pages\CreateRecord;
use Carbon\Carbon;

class CreateContract extends CreateRecord
{
    protected static string $resource = ContractResource::class;

    protected function afterCreate(): void
    {
        $contract = $this->record;
        $templateId = $this->data['payment_template_id'] ?? null;

        if ($templateId) {
            $template = PaymentTemplate::find($templateId);
            
            // 1. Tạo Schedule cho Hợp đồng
            $schedule = PaymentSchedule::create([
                'contract_id' => $contract->id,
                'template_id' => $template->id,
            ]);

            // 2. Clone từng Item từ Template sang Schedule thực tế
            $items = $template->items()->orderBy('installment_no')->get();
            $lastDueDate = Carbon::parse($contract->signing_date);

            foreach ($items as $item) {
                $dueDate = null;

                // Logic tính ngày đến hạn chuẩn v5.5
                if ($item->days_after_signing !== null) {
                    $dueDate = Carbon::parse($contract->signing_date)->addDays($item->days_after_signing);
                } elseif ($item->days_after_previous !== null) {
                    $dueDate = $lastDueDate->copy()->addDays($item->days_after_previous);
                } elseif ($item->due_date !== null) {
                    $dueDate = $item->due_date;
                }

                PaymentScheduleItem::create([
                    'schedule_id' => $schedule->id,
                    'installment_no' => $item->installment_no,
                    'type' => $item->type,
                    'percentage' => $item->percentage,
                    'amount' => $contract->total_value * ($item->percentage / 100),
                    'due_date' => $dueDate,
                ]);

                if ($dueDate) {
                    $lastDueDate = $dueDate;
                }
            }
        }
    }
}
