<?php
declare(strict_types=1);

namespace App\Modules\ActivitySubscriptions\Services;

use App\Core\App;
use App\Modules\ActivitySubscriptions\Models\ActivityPricing;

class ActivityPricingService
{
    /**
     * Get the rate pair (member / nonmember) for a pricing type and reference.
     *
     * @return array{member_rate: string, nonmember_rate: string}
     */
    public static function getRate(string $pricingType, int $referenceId): array
    {
        $today = date('Y-m-d');

        $row = ActivityPricing::query()
            ->where('pricing_type', '=', $pricingType)
            ->where('reference_id', '=', $referenceId)
            ->where('is_active', '=', 1)
            ->whereRaw('`effective_from` <= ?', [$today])
            ->whereRaw('(`effective_to` IS NULL OR `effective_to` >= ?)', [$today])
            ->orderBy('effective_from', 'DESC')
            ->first();

        if (!$row) {
            return ['member_rate' => '0.00', 'nonmember_rate' => '0.00'];
        }

        return [
            'member_rate'    => (string) ($row['member_rate'] ?? '0.00'),
            'nonmember_rate' => (string) ($row['nonmember_rate'] ?? '0.00'),
        ];
    }

    /**
     * Get the effective rate for a specific pricing type, reference, membership, and time tier.
     */
    public static function getEffectiveRate(
        string $pricingType,
        int $referenceId,
        bool $isMember,
        ?string $timeTier = 'AM'
    ): float {
        return ActivityPricing::getEffectiveRate($pricingType, $referenceId, $isMember, $timeTier);
    }

    /**
     * Upsert a pricing record.
     *
     * If an active record exists for the same type + reference, deactivates it
     * and creates a new one.
     *
     * @param array $rates Keys: member_rate, nonmember_rate, member_rate_pm, nonmember_rate_pm, effective_from, effective_to
     */
    public static function setRate(string $pricingType, int $referenceId, array $rates): object
    {
        $db = App::getInstance()->db();

        // Deactivate any current active pricing for this type + reference
        $db->query(
            "UPDATE `activity_pricing` SET `is_active` = 0, `updated_at` = ? WHERE `pricing_type` = ? AND `reference_id` = ? AND `is_active` = 1",
            [date('Y-m-d H:i:s'), $pricingType, $referenceId]
        );

        $employee = App::getInstance()->currentEmployee();

        return ActivityPricing::create([
            'pricing_type'      => $pricingType,
            'reference_id'      => $referenceId,
            'member_rate'       => $rates['member_rate'] ?? '0.00',
            'nonmember_rate'    => $rates['nonmember_rate'] ?? '0.00',
            'member_rate_pm'    => $rates['member_rate_pm'] ?? '0.00',
            'nonmember_rate_pm' => $rates['nonmember_rate_pm'] ?? '0.00',
            'effective_from'    => $rates['effective_from'] ?? date('Y-m-d'),
            'effective_to'      => $rates['effective_to'] ?? null,
            'is_active'         => 1,
            'created_by'        => $employee ? (int) ($employee->id ?? ($employee['id'] ?? null)) : null,
        ]);
    }
}
