<?php
declare(strict_types=1);

namespace App\Modules\Pricing\Models;

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

class BoardOffer extends Model
{
    protected static string $table = 'board_offers';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'title_ar', 'title_en', 'description',
        'cash_discount_type', 'cash_discount_value',
        'inst_down_payment_pct', 'inst_months', 'inst_interest_rate',
        'inst_grace_type', 'inst_grace_months', 'inst_post_grace_rate',
        'branch_id', 'applies_to', 'effective_from', 'effective_to',
        'is_active', 'board_decision_number', 'board_decision_date', 'notes',
        'created_by', 'updated_by',
    ];

    public static function getActiveOffers(?int $branchId = null): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        $where = "`is_active` = 1 AND `effective_from` <= ? AND `effective_to` >= ?";
        $params = [$today, $today];

        if ($branchId !== null) {
            $where .= " AND (`branch_id` IS NULL OR `branch_id` = ?)";
            $params[] = $branchId;
        }

        return $db->select(
            "SELECT * FROM `board_offers` WHERE {$where} ORDER BY `branch_id` DESC, `effective_from` DESC",
            $params
        );
    }

    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 (`title_ar` LIKE ? OR `title_en` LIKE ? OR `board_decision_number` LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s;
            $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 `board_offers` WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

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

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