<?php
declare(strict_types=1);

namespace App\Modules\Pricing\Models;

use App\Core\Model;
use App\Core\App;

class SpecialDiscount extends Model
{
    protected static string $table = 'special_discounts';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'name_ar', 'name_en', 'discount_percentage', 'discount_type',
        'applies_to', 'effective_from', 'effective_to', 'fixed_amount',
        'condition_type', 'condition_min_amount', 'bonus_free_subscription_years',
        'requires_document', 'description', 'is_active',
    ];

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');
        return $db->select(
            "SELECT * FROM `special_discounts` WHERE `is_active` = 1 AND (effective_from IS NULL OR effective_from <= ?) AND (effective_to IS NULL OR effective_to >= ?) ORDER BY `name_ar`",
            [$today, $today]
        );
    }

    public static function allActiveUnfiltered(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM `special_discounts` WHERE `is_active` = 1 ORDER BY `name_ar`"
        );
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['search'])) {
            $where .= ' AND (`name_ar` LIKE ? OR `name_en` LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s;
            $params[] = $s;
        }
        if ($filters['is_active'] ?? '' !== '') {
            $where .= ' AND `is_active` = ?';
            $params[] = (int) $filters['is_active'];
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM `special_discounts` WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $data = $db->select(
            "SELECT * FROM `special_discounts` WHERE {$where} ORDER BY `name_ar` LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return [
            'data' => $data,
            'pagination' => \App\Core\Pagination::paginate($total, $perPage, $page),
        ];
    }
}
