<?php

namespace App\Models;

use App\Traits\HasTranslatedName;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory, HasTranslatedName;

    protected $table = 'state1_countries';

    protected $fillable = [
        'name',
        'name_en',
        'iso_code',
        'iso_code3',
        'num_code',
        'phone_code',
        'currency_code',
        'capital',
        'region',
        'subregion',
        'boundaries',
        'area',
        'population',
        'timezone',
        'continent',
        'tld',
        'native_name',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'area' => 'decimal:2',
        'population' => 'integer',
    ];

    /**
     * Get the boundaries data in properly formatted GeoJSON
     */
    public function getBoundariesAttribute($value)
    {
        if (!$value) {
            return null;
        }

        // Check if this might be binary or corrupted data
        if (!is_string($value)) {
            return is_array($value) || is_object($value) ? json_encode($value) : (string) $value;
        }

        // If it's a WKT string, try to convert it to GeoJSON using MySQL
        if (strpos($value, 'POLYGON') === 0 || strpos($value, 'MULTIPOLYGON') === 0) {
            try {
                // Use MySQL to convert WKT to GeoJSON
                $result = \DB::select("SELECT ST_AsGeoJSON(ST_GeomFromText(?)) as geojson", [$value]);
                if (!empty($result) && isset($result[0]->geojson)) {
                    return $result[0]->geojson;
                }
            } catch (\Exception $e) {
                \Log::warning('Failed to convert WKT to GeoJSON: ' . $e->getMessage());
            }
            // Return the WKT as is if conversion fails
            return $value;
        }

        // If it's already JSON, validate and return
        if ($this->isValidJSON($value)) {
            return $value;
        }

        return $value;
    }

    /**
     * Set the boundaries value for proper storage
     */
    public function setBoundariesAttribute($value)
    {
        if (!$value) {
            $this->attributes['boundaries'] = null;
            return;
        }

        // If value is a WKT string (for MySQL GEOMETRY type)
        if (is_string($value) && (
            strpos($value, 'POLYGON') === 0 ||
            strpos($value, 'MULTIPOLYGON') === 0 ||
            strpos($value, 'LINESTRING') === 0
        )) {
            // Store as is for GEOMETRY columns
            $this->attributes['boundaries'] = $value;
            return;
        }

        // For JSON storage
        try {
            // If it's already a string but not WKT, check if it's valid JSON
            if (is_string($value)) {
                json_decode($value);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $this->attributes['boundaries'] = $value;
                    return;
                }
            }

            // If it's an array or object, encode it
            if (is_array($value) || is_object($value)) {
                $this->attributes['boundaries'] = json_encode($value);
                return;
            }

            // Default case
            $this->attributes['boundaries'] = (string) $value;
        } catch (\Exception $e) {
            \Log::error('Error setting boundaries: ' . $e->getMessage());
            $this->attributes['boundaries'] = null;
        }
    }

    /**
     * Check if a string is valid JSON
     */
    protected function isValidJSON($string)
    {
        json_decode($string);
        return json_last_error() == JSON_ERROR_NONE;
    }

    // Relationships
    public function provinces()
    {
        return $this->hasMany(Province::class);
    }

    public function locations()
    {
        return $this->hasMany(Location::class);
    }
}
