<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $fillable = [
        'approval_date', 'name', 'surname', 'date_of_birth', 'fiscal_code',
        'email', 'phone', 'address', 'type_of_case',
        'solution_id', 'sub_solution_id',
        'academy_id', 'sub_academy_id',
        'other', 'in_charger', 'total_agreed_amount',
        'cash_deposit_in_office', 'cash_deposit', 'bank_deposit', 'bd_deposit',
        'balance_due', 'paid_to', 'notes', 'is_active', 'color'
    ];

    public function solution() {
        return $this->belongsTo(Solution::class, 'solution_id');
    }

    public function subSolution() {
        return $this->belongsTo(Solution::class, 'sub_solution_id');
    }

    public function academy() {
        return $this->belongsTo(Academy::class, 'academy_id');
    }

    public function subAcademy() {
        return $this->belongsTo(Academy::class, 'sub_academy_id');
    }

    protected static function booted()
{
    static::updating(function ($client) {
        // Check if status changed from inactive → active
        if (
            $client->isDirty('is_active') &&
            $client->getOriginal('is_active') == 0 &&
            $client->is_active == 1
        ) {
            // Set approval_date only the first time
            if ($client->approval_date === null) {
                $client->approval_date = now()->format('Y-m-d');
            }
        }
    });
}


    protected $casts = [
        'is_active' => 'boolean',
    ];
}
