<?php

namespace App\Models;

use CodeIgniter\Model;

class DiscountUsageModel extends Model
{
    protected $table = 'discount_usages';
    protected $primaryKey = 'id';
    
    protected $allowedFields = [
        'voucher_id',
        'invoice_id',
        'discount_amount',
        'school_year',
        'semester',
        'updated_by',
        'parent_id',
        'used_at'
    ];
   
    // Enable automatic timestamps if desired (optional: only if you add created_at/updated_at columns)
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    // Add validation rules
    protected $validationRules = [
        'voucher_id' => 'required|is_natural_no_zero',
        'invoice_id' => 'required|is_natural_no_zero',
        'user_id'    => 'permit_empty|is_natural_no_zero',
        'used_at'    => 'valid_date'
    ];

    protected $validationMessages = [
        'voucher_id' => [
            'required' => 'Voucher ID is required.'
        ],
        'invoice_id' => [
            'required' => 'Invoice ID is required.'
        ]
    ];

    public function getTotalDiscountByParentIdAndSchoolYear(int $parentId, string $schoolYear): float
    {
        $db = \Config\Database::connect();

        $result = $db->table('discount_usages du')
            ->selectSum('du.discount_amount', 'total_discount')
            ->join('invoices i', 'du.invoice_id = i.id')
            ->where('i.parent_id', $parentId)
            ->where('i.school_year', $schoolYear)
            ->get()
            ->getRowArray();

        return $result && isset($result['total_discount']) ? (float) $result['total_discount'] : 0.00;
    }

}

