<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Models\FeeConfig;

class SocUnit extends Model
{
    use HasFactory;

    protected $table = 'soc_units';
    protected $primaryKey = 'SU_ID';
    public $timestamps = true;

    protected $fillable = [
        'SB_Id',
        'UT_Id',
        'Unit_No',
    ];

    public function block()
    {
        return $this->belongsTo(SocBlock::class, 'SB_Id', 'SB_Id');
    }

    public function unitType()
    {
        return $this->belongsTo(UnitType::class, 'UT_Id', 'UT_Id');
    }

    /**
     * Boot method to handle model events
     */
    protected static function boot()
    {
        parent::boot();

        // Deleting event to remove associated FeeConfig records
        static::deleting(function ($socUnit) {
            try {
                // Fetch FeeConfig records for the same SocId
                $feeConfigs = FeeConfig::where('SocId', $socUnit->unitType->SocId)->get();

                foreach ($feeConfigs as $feeConfig) {
                    $unitsData = json_decode($feeConfig->units, true) ?? [];
                    // Remove the SU_ID from the units array
                    $updatedUnits = array_filter($unitsData, function ($unit) use ($socUnit) {
                        return isset($unit['SU_ID']) && (int)$unit['SU_ID'] !== (int)$socUnit->SU_ID;
                    });

                    if (count($updatedUnits) !== count($unitsData)) {
                        if (empty($updatedUnits)) {
                            // If no units remain, delete the FeeConfig
                            $feeConfig->delete();
                            Log::info('Deleted FeeConfig due to empty units after SocUnit deletion', [
                                'FC_Id' => $feeConfig->FC_Id,
                                'SU_ID' => $socUnit->SU_ID,
                                'SocId' => $socUnit->unitType->SocId,
                            ]);
                        } else {
                            // Update the FeeConfig with the modified units array
                            $feeConfig->units = json_encode(array_values($updatedUnits));
                            $feeConfig->save();
                            Log::info('Updated FeeConfig by removing SU_ID from units', [
                                'FC_Id' => $feeConfig->FC_Id,
                                'SU_ID' => $socUnit->SU_ID,
                                'SocId' => $socUnit->unitType->SocId,
                            ]);
                        }
                    }
                }
            } catch (\Exception $e) {
                Log::error('Error deleting related FeeConfig for SocUnit:', [
                    'SU_ID' => $socUnit->SU_ID,
                    'SocId' => $socUnit->unitType->SocId ?? 'unknown',
                    'error' => $e->getMessage(),
                ]);
                throw $e; // Re-throw to prevent silent failures
            }
        });
    }
}
