<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PlotSurvey extends Model
{
    protected $fillable = [
        'feasibility_report_id', 'user_id',
        'survey_file_path', 'survey_file_type', 'original_filename',
        'ai_status', 'ai_error',
        'extracted_area_sqm', 'extracted_area_sqyd',
        'road_frontage_m', 'plot_length_m', 'plot_width_m',
        'survey_number', 'village_name', 'taluka_name', 'district_name',
        'land_use_type', 'ownership_type',
        'plot_shape_points', 'ai_analysis_raw', 'dimensions_detected',
        'area_confirmed', 'confirmed_area_sqm',
        'bhulekh_survey_no', 'bhulekh_state', 'bhulekh_data', 'bhulekh_fetched_at',
    ];

    protected $casts = [
        'extracted_area_sqm'    => 'float',
        'extracted_area_sqyd'   => 'float',
        'road_frontage_m'       => 'float',
        'plot_length_m'         => 'float',
        'plot_width_m'          => 'float',
        'confirmed_area_sqm'    => 'float',
        'plot_shape_points'     => 'array',
        'ai_analysis_raw'       => 'array',
        'dimensions_detected'   => 'array',
        'bhulekh_data'          => 'array',
        'area_confirmed'        => 'boolean',
        'bhulekh_fetched_at'    => 'datetime',
    ];

    public function feasibilityReport(): BelongsTo
    {
        return $this->belongsTo(FeasibilityReport::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /** The final confirmed area to use (confirmed by user, else AI-extracted) */
    public function getEffectiveAreaSqmAttribute(): ?float
    {
        if ($this->area_confirmed && $this->confirmed_area_sqm) {
            return $this->confirmed_area_sqm;
        }
        return $this->extracted_area_sqm;
    }
}
