<?php

namespace App\Models;

use CodeIgniter\Model;

class RewardModel extends Model
{
    protected $table = 'rewards';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'item_id', 'discount_type', 'discount_value', 'points_required', 'start_date', 'end_date', 'is_active', 'created_at'];
    protected $useTimestamps = false;

    public function getWithItemNames(): array
    {
        return $this->select('rewards.*, items.name as item_name, items.price as item_price')
            ->join('items', 'items.id = rewards.item_id', 'left')
            ->orderBy('rewards.id', 'DESC')
            ->findAll();
    }

    public function calculateDiscount(array $reward, int $originalPrice): int
    {
        if ($reward['discount_type'] === 'percent') {
            $discount = (int) round($originalPrice * ((int) $reward['discount_value'] / 100));
        } else {
            $discount = (int) $reward['discount_value'];
        }

        return min($discount, $originalPrice);
    }

    public function isAvailableToday(array $reward): bool
    {
        if ((int) ($reward['is_active'] ?? 0) !== 1) {
            return false;
        }

        $today = date('Y-m-d');
        if (!empty($reward['start_date']) && $reward['start_date'] > $today) {
            return false;
        }
        if (!empty($reward['end_date']) && $reward['end_date'] < $today) {
            return false;
        }

        return true;
    }
}
