<?php

namespace App\Models;

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

class CartItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'session_id',
        'product_id',
        'quantity',
        'include_installation',
    ];

    protected $casts = [
        'include_installation' => 'boolean',
    ];

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

    /**
     * Product relationship
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Get subtotal for this cart item
     */
    public function getSubtotalAttribute(): float
    {
        return $this->product->effective_price * $this->quantity;
    }

    /**
     * Get installation cost for this item
     */
    public function getInstallationCostAttribute(): float
    {
        if (!$this->include_installation || !$this->product->requires_installation) {
            return 0;
        }
        return ($this->product->installation_price ?? 0) * $this->quantity;
    }

    /**
     * Get total for this item including installation
     */
    public function getTotalAttribute(): float
    {
        return $this->subtotal + $this->installation_cost;
    }

    /**
     * Scope for user's cart
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope for session cart (guest users)
     */
    public function scopeForSession($query, $sessionId)
    {
        return $query->where('session_id', $sessionId);
    }
}
