<?php

namespace App\Models;

use CodeIgniter\Model;

class ContractMilestoneModel extends Model
{
    protected $table         = 'contract_milestones';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'contract_id', 'title', 'due_date', 'amount', 'status', 'sort_order', 'created_at',
    ];

    public function getForContract(int $contractId): array
    {
        return $this->where('contract_id', $contractId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForContract(int $contractId, array $milestones): void
    {
        $this->where('contract_id', $contractId)->delete();
        $now = date('Y-m-d H:i:s');
        $sort = 0;

        foreach ($milestones as $item) {
            $title = trim((string) ($item['title'] ?? ''));
            if ($title === '') {
                continue;
            }

            $this->insert([
                'contract_id' => $contractId,
                'title'       => $title,
                'due_date'    => trim((string) ($item['due_date'] ?? '')) ?: null,
                'amount'      => (float) ($item['amount'] ?? 0),
                'status'      => in_array($item['status'] ?? 'pending', ['pending', 'done'], true)
                    ? ($item['status'] ?? 'pending')
                    : 'pending',
                'sort_order'  => $sort++,
                'created_at'  => $now,
            ]);
        }
    }
}
