<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class DiscountUsage extends BaseModel
{
    protected $table = 'discount_usages';

    // ✅ CI: timestamps enabled (created_at / updated_at)
    public $timestamps = true;

    protected $fillable = [
        'voucher_id',
        'invoice_id',
        'parent_id',
        'discount_amount',
        'description',
        'school_year',
        'updated_by',
        'used_at',
        'created_at',
        'updated_at',
        'semester',
    ];

    protected $casts = [
        'voucher_id'       => 'integer',
        'invoice_id'       => 'integer',
        'discount_amount'  => 'decimal:2',  // adjust precision if needed
        'updated_by'       => 'integer',
        'parent_id'        => 'integer',
        'used_at'          => 'datetime',
    ];

    /* Optional relationships */
    public function invoice()
    {
        return $this->belongsTo(Invoice::class, 'invoice_id');
    }

    public function voucher()
    {
        return $this->belongsTo(Voucher::class, 'voucher_id');
    }

    /**
     * Equivalent of CI getTotalDiscountByParentIdAndSchoolYear()
     */
    public static function getTotalDiscountByParentIdAndSchoolYear(int $parentId, string $schoolYear): float
    {
        $total = DB::table('discount_usages as du')
            ->join('invoices as i', 'du.invoice_id', '=', 'i.id')
            ->where('i.parent_id', $parentId)
            ->where('i.school_year', $schoolYear)
            ->sum('du.discount_amount');

        return (float) $total;
    }
}