<?php
// app/Models/DetailPenjualan.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DetailPenjualan extends Model
{
    protected $table = 'detail_penjualan';
    protected $primaryKey = 'detail_id';
    protected $fillable = [
        'penjualan_id',
        'produk_id',
        'harga_satuan',
        'jumlah',
        'subtotal',
        'foto_produk'  
    ];

    public function penjualan()
    {
        return $this->belongsTo(Penjualan::class, 'penjualan_id', 'penjualan_id');
    }

    public function produk()
    {
        return $this->belongsTo(Product::class, 'produk_id', 'produk_id');
    }
    
    // Relasi ke review
    public function review()
    {
        return $this->hasOne(Review::class, 'produk_id', 'produk_id')
            ->where('penjualan_id', $this->penjualan_id)
            ->where('user_id', auth()->id());
    }
    
    // Cek apakah produk sudah direview oleh user dalam transaksi ini
    public function hasReview()
    {
        return Review::where('produk_id', $this->produk_id)
            ->where('user_id', auth()->id())
            ->where('penjualan_id', $this->penjualan_id)
            ->exists();
    }
    
    // Dapatkan review jika ada
    public function getReview()
    {
        return Review::where('produk_id', $this->produk_id)
            ->where('user_id', auth()->id())
            ->where('penjualan_id', $this->penjualan_id)
            ->first();
    }
}