<?php

namespace App\Models\SelfPaced;

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

/**
 * BookPurchase Model
 *
 * Records course book purchases. Not tied to an enrollment — identified by email.
 *
 * Requirements: 9.8, 9.10
 */
class BookPurchase extends Model
{
    protected $table = 'self_paced_book_purchases';

    protected $fillable = [
        'course_id',
        'user_id',
        'email',
        'payment_reference',
        'payment_method',
        'amount_paid',
        'currency',
        'proof_id',
        'download_token',
        'downloaded_at',
        'payment_date',
    ];

    protected $casts = [
        'amount_paid' => 'decimal:2',
        'downloaded_at' => 'datetime',
        'payment_date' => 'datetime',
    ];

    // =====================================================================
    // Relationships
    // =====================================================================

    public function course(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(related: \App\Models\User::class, 'user_id');
    }

    public function proof(): BelongsTo
    {
        return $this->belongsTo(PaymentProof::class, 'proof_id');
    }

    // =====================================================================
    // Methods
    // =====================================================================

    /**
     * Check if book has been downloaded
     *
     * @return bool
     */
    public function hasBeenDownloaded(): bool
    {
        return $this->downloaded_at !== null;
    }

    /**
     * Record that the book was downloaded
     *
     * @return void
     */
    public function recordDownload(): void
    {
        $this->update(['downloaded_at' => now()]);
    }
}
