<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Products extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'sub_category_id',
        // 'country_id',
        'name',
        'slug',
        'description',
        'price',
        'discount_price',
        'stock',
        'status',
        'product_type',
        'custom_photo',
        'custom_text',
        'custom_message',
        'custom_color',
        'voucher_amount',
        'voucher_brand',
        'voucher_start_date',
        'voucher_end_date',
        'voucher_value',
        'voucher_code',
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];
    public function images()
    {
        // ✅ correct relationship
        return $this->hasMany(ProductImage::class, 'product_id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function subCategory()
    {
        return $this->belongsTo(SubCategory::class);
    }

    public function countries()
    {
        return $this->belongsToMany(Country::class, 'products_country', 'product_id', 'country_id');
    }

    

    public function firstImage()
    {
        return $this->hasOne(ProductImage::class, 'product_id')->orderBy('id');
    }


    public function getFirstImageUrlAttribute()
    {
        $image = $this->images()->first();

        if (!$image) {
            return null;
        }

        if (str_starts_with($image->image, 'http')) {
            return $image->image;
        }

        return url('/uploads/products/' . $image->image);
    }

    protected $appends = ['first_image_url', 'discount_percentage', 'final_discount_price'];
    public function getFinalPriceAttribute()
    {
        if (!$this->discount_price) {
            return $this->price;
        }

        return $this->price - ($this->price * $this->discount_price / 100);
    }
    public function getDiscountPercentageAttribute()
    {
        if (!$this->discount_price) {
            return 0;
        }

        return $this->discount_price; // already in percentage
    }

    public function getFinalDiscountPriceAttribute()
    {
        if (!$this->discount_price) {
            return $this->price; // no discount
        }

        // discount_price = percentage
        $discountAmount = ($this->price * $this->discount_price) / 100;

        return round($this->price - $discountAmount);
    }
}
