<?php
declare(strict_types=1);

namespace App\Modules\ServiceCatalog\Models;

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

class ServicePrice extends Model
{
    protected static string $table = 'service_catalog';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'service_code', 'name_ar', 'name_en', 'price_type', 'base_amount',
        'percentage', 'annual_amount', 'currency', 'applies_to', 'branch_id',
        'effective_from', 'effective_to', 'is_active',
    ];

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select("
            SELECT sc.*, b.name_ar as branch_name
            FROM service_catalog sc
            LEFT JOIN branches b ON b.id = sc.branch_id
            WHERE sc.is_active = 1
            ORDER BY sc.service_code
        ");
    }

    /**
     * Get the current price for a service by code.
     * Returns base_amount for fixed prices, or the full row for percentage-based.
     * Uses effective_from/effective_to to find the currently valid price.
     * Falls back to $default if the service code is not found.
     */
    public static function getPrice(string $serviceCode, ?string $default = null, ?int $branchId = null): ?string
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        // Try branch-specific first, then global
        $sql = "SELECT base_amount FROM service_catalog
                WHERE service_code = ? AND is_active = 1
                AND effective_from <= ?
                AND (effective_to IS NULL OR effective_to >= ?)";

        if ($branchId !== null) {
            $row = $db->selectOne($sql . " AND branch_id = ? ORDER BY effective_from DESC LIMIT 1", [$serviceCode, $today, $today, $branchId]);
            if ($row) return $row['base_amount'];
        }

        $row = $db->selectOne($sql . " AND branch_id IS NULL ORDER BY effective_from DESC LIMIT 1", [$serviceCode, $today, $today]);
        return $row ? $row['base_amount'] : $default;
    }

    /**
     * Get the full service catalog row (for percentage-based services).
     */
    public static function getServiceRow(string $serviceCode, ?int $branchId = null): ?array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        $sql = "SELECT * FROM service_catalog
                WHERE service_code = ? AND is_active = 1
                AND effective_from <= ?
                AND (effective_to IS NULL OR effective_to >= ?)";

        if ($branchId !== null) {
            $row = $db->selectOne($sql . " AND branch_id = ? ORDER BY effective_from DESC LIMIT 1", [$serviceCode, $today, $today, $branchId]);
            if ($row) return $row;
        }

        return $db->selectOne($sql . " AND branch_id IS NULL ORDER BY effective_from DESC LIMIT 1", [$serviceCode, $today, $today]);
    }
}