<?php

namespace App\Models;

use App\Components\Functions;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class RoomNeedMore extends Model
{
    //
    use SoftDeletes;

    const UNDER_20 = 1;
    const FROM_20_TO_30 = 2;
    const OVER_30 = 3;

    protected $fillable = [
        'gender',
        'age',
        'number_peoples',
        'province',
        'district',
        'ward',
        'address',
        'price',
        'deposit',
        'date_available',
        'amenities',
        'policies',
        'images',
        'image',
        'desc',
        'owner_name',
        'owner_phone',
        'size',
        'created_at',
        'updated_at',
        'deleted_at',
        'name',
        'user_id',
        'lng',
        'lat',
        'compress_image',
    ];

    public function owner()
    {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
        'date_available'
    ];

    public function getDescAttribute()
    {
        $desc = $this->attributes['desc'];
        return $desc;
        // return preg_replace("/\+?[0-9][0-9()\-.\s+]{7,20}[0-9]/", ' xxxxxxx ', $desc);
    }

    public function getAddressAttribute()
    {
        if (str_contains(request()->fullUrl(), 'api/v1')) {
            $addressDetail = $this->getAddressDetailAttribute();
            if (!empty($addressDetail)) {
                return $this->attributes['address'] . ', ' . $addressDetail;
            }
        }

        return $this->attributes['address'];
    }

    public function getAddressDetailAttribute()
    {
        $district = $this->attributes['district'];
        $province = $this->attributes['province'];
        $ward = $this->attributes['ward'];
        $districtText = '';
        $provinceText = '';
        $wardText = '';

        if (!empty($district)) {
            $districtItem = Functions::getDistrictName($district);
            if ($districtItem) {
                $districtText = $districtItem->name . ', ';
            }
        }

        if (!empty($province)) {
            $provinceItem = Functions::getProvinceName($province);
            if ($provinceItem) {
                $provinceText = $provinceItem->name;
            }
        }

        if (!empty($ward)) {
            $wardItem = Functions::getWardName($ward);
            if ($wardItem) {
                $wardText = $wardItem->name . ', ';
            }
        }
        return trim($wardText . $districtText . $provinceText);
    }

    public function scopeIsWithinMaxDistance($query, $coordinates, $radius = 5)
    {
        $haversine = "(6371 * acos(cos(radians(" . $coordinates['lat'] . ")) 
                    * cos(radians(`lat`)) 
                    * cos(radians(`lng`) 
                    - radians(" . $coordinates['lng'] . ")) 
                    + sin(radians(" . $coordinates['lat'] . ")) 
                    * sin(radians(`lat`))))";

        return $query->select('*')
            ->selectRaw("{$haversine} AS distance")
            ->whereRaw("{$haversine} < ?", [$radius]);
    }

    public function getDepositTextAttribute()
    {
        $deposit = $this->attributes['deposit'];
        if (empty($deposit)) {
            return 'Thỏa thuận';
        }

        return number_format($deposit, 0, '.', '.') . 'đ';
    }

    public function getDateAvailableTextAttribute()
    {
        $date = $this->attributes['date_available'];
        if (empty($date)) {
            return 'Thỏa thuận';
        }
        try {

            $dt = Carbon::createFromFormat('Y-m-d', $date)->format('d/m/Y');

        } catch (\Exception $ex) {
            $dt = 'Thỏa thuận';
        }

        return $dt;
    }

    public function getNumberPeoplesTextAttribute()
    {
        $number = $this->attributes['number_peoples'];
        $gender = $this->attributes['gender'];

        if ($gender != 'Khác') {
            return Functions::getNumber($number) . ' ' . strtolower($gender);
        }

        return Functions::getNumber($number) . ' bạn';
    }

    public function getPriceTextAttribute()
    {
        $price = $this->attributes['price'];
        if (empty($price)) {
            return 'Thỏa thuận';
        }

        return number_format($price, 0, '.', '.') . 'đ';
    }

    public function getImageAttribute()
    {
        $image = $this->attributes['image'];

//        if(!empty($this->attributes['compress_image']))
//        {
//            $image = $this->attributes['compress_image'];
//        }

        if (empty($image)) {
            if (!str_contains(request()->fullUrl(), 'api/v1')) {
                return '/frontend3/assets/img/placeholder.png';
            }
        }

        if (str_contains($image, 'http')) {
            return $image;
        }

        if (str_contains($image, '/files/')) {
            return '/files/' . str_replace('/files/', '', $image);
        }

        if (!str_contains($image, 'http') && !str_contains($image, '/files')) {
            return '/files/' . $image;
        }

        return $image;
    }
}
