<?php

// Feature: student-search-officer-wallet-access, Property 19: Dashboard disabled-state rendering reflects settings flags

declare(strict_types=1);

namespace Tests;

use PHPUnit\Framework\TestCase;

require_once __DIR__ . '/../includes/wallet_helpers.php';

/**
 * Task 1.1 — Property test for dashboard disabled-state rendering (Property 19).
 * Validates: Requirements 2.3, 2.4
 */
class OfficerDashboardDisabledStateTest extends TestCase
{
    private \mysqli $con;

    protected function setUp(): void
    {
        $host = defined('DB_SERVER') ? DB_SERVER : 'localhost';
        $user = defined('DB_USER')   ? DB_USER   : 'root';
        $pass = defined('DB_PASS')   ? DB_PASS   : '';
        $name = defined('DB_NAME')   ? DB_NAME   : 'sms';

        $this->con = new \mysqli($host, $user, $pass, $name);

        if ($this->con->connect_error) {
            $this->markTestSkipped('Cannot connect to DB: ' . $this->con->connect_error);
        }

        // Ensure wallet_settings table exists with required rows
        $this->con->query("
            CREATE TABLE IF NOT EXISTS wallet_settings (
                id INT PRIMARY KEY AUTO_INCREMENT,
                setting_key VARCHAR(100) UNIQUE NOT NULL,
                setting_value VARCHAR(255) NOT NULL DEFAULT '',
                label VARCHAR(255) NOT NULL DEFAULT '',
                description TEXT,
                updated_at DATETIME DEFAULT NULL,
                updated_by INT DEFAULT NULL
            )
        ");
        $this->con->query("
            INSERT IGNORE INTO wallet_settings (setting_key, setting_value, label) VALUES
                ('payments_enabled',  '1', 'Enable Wallet Payments'),
                ('transfers_enabled', '1', 'Enable Wallet Transfers')
        ");
    }

    protected function tearDown(): void
    {
        // Restore defaults
        $this->con->query("UPDATE wallet_settings SET setting_value='1' WHERE setting_key='payments_enabled'");
        $this->con->query("UPDATE wallet_settings SET setting_value='1' WHERE setting_key='transfers_enabled'");
        $this->con->close();
    }

    // -----------------------------------------------------------------------
    // Helper: replicate the dashboard card anchor rendering logic
    // -----------------------------------------------------------------------

    /**
     * Mirrors the anchor HTML produced by dashboard2.php for a given disabled flag.
     */
    private function renderAnchorHtml(bool $disabled, string $baseClass, string $href, string $id): string
    {
        $extraClass = $disabled ? ' opacity-50 pointer-events-none' : '';
        $titleAttr  = $disabled ? ' title="Currently disabled by administrator"' : '';
        return '<a href="' . $href . '" class="' . $baseClass . $extraClass . '" id="' . $id . '"' . $titleAttr . '>';
    }

    // -----------------------------------------------------------------------
    // Property 19: Dashboard disabled-state rendering reflects settings flags
    // -----------------------------------------------------------------------

    /**
     * @dataProvider flagCombinationsProvider
     */
    public function testPayFeeCardReflectsPaymentsEnabledFlag(int $payments_enabled, int $transfers_enabled): void
    {
        // Write flags to DB and read them back (same as dashboard2.php does)
        $this->con->query("UPDATE wallet_settings SET setting_value='{$payments_enabled}' WHERE setting_key='payments_enabled'");
        $this->con->query("UPDATE wallet_settings SET setting_value='{$transfers_enabled}' WHERE setting_key='transfers_enabled'");

        $pe = (int)getWalletSetting($this->con, 'payments_enabled', 1);
        $te = (int)getWalletSetting($this->con, 'transfers_enabled', 1);

        $baseClass = 'text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter';

        $payAnchor      = $this->renderAnchorHtml(!$pe, $baseClass, 'small_wallet_pay_fee.php', 'payStudentFeeBtn');
        $transferAnchor = $this->renderAnchorHtml(!$te, $baseClass, 'small_transfer_funds.php', 'transferFundsBtn');

        if ($payments_enabled === 0) {
            $this->assertStringContainsString(
                'opacity-50',
                $payAnchor,
                "Pay Fee anchor must contain opacity-50 when payments_enabled=0"
            );
            $this->assertStringContainsString(
                'pointer-events-none',
                $payAnchor,
                "Pay Fee anchor must contain pointer-events-none when payments_enabled=0"
            );
            $this->assertStringContainsString(
                'title="Currently disabled by administrator"',
                $payAnchor,
                "Pay Fee anchor must have disabled title when payments_enabled=0"
            );
        } else {
            $this->assertStringNotContainsString(
                'opacity-50',
                $payAnchor,
                "Pay Fee anchor must NOT contain opacity-50 when payments_enabled=1"
            );
            $this->assertStringNotContainsString(
                'pointer-events-none',
                $payAnchor,
                "Pay Fee anchor must NOT contain pointer-events-none when payments_enabled=1"
            );
            $this->assertStringNotContainsString(
                'title="Currently disabled by administrator"',
                $payAnchor,
                "Pay Fee anchor must NOT have disabled title when payments_enabled=1"
            );
        }

        if ($transfers_enabled === 0) {
            $this->assertStringContainsString(
                'opacity-50',
                $transferAnchor,
                "Transfer anchor must contain opacity-50 when transfers_enabled=0"
            );
            $this->assertStringContainsString(
                'pointer-events-none',
                $transferAnchor,
                "Transfer anchor must contain pointer-events-none when transfers_enabled=0"
            );
            $this->assertStringContainsString(
                'title="Currently disabled by administrator"',
                $transferAnchor,
                "Transfer anchor must have disabled title when transfers_enabled=0"
            );
        } else {
            $this->assertStringNotContainsString(
                'opacity-50',
                $transferAnchor,
                "Transfer anchor must NOT contain opacity-50 when transfers_enabled=1"
            );
            $this->assertStringNotContainsString(
                'pointer-events-none',
                $transferAnchor,
                "Transfer anchor must NOT contain pointer-events-none when transfers_enabled=1"
            );
            $this->assertStringNotContainsString(
                'title="Currently disabled by administrator"',
                $transferAnchor,
                "Transfer anchor must NOT have disabled title when transfers_enabled=1"
            );
        }
    }

    /**
     * Generates 100 random combinations of payments_enabled (0|1) and transfers_enabled (0|1).
     */
    public static function flagCombinationsProvider(): array
    {
        $cases = [];
        for ($i = 0; $i < 100; $i++) {
            $cases["iteration_{$i}"] = [random_int(0, 1), random_int(0, 1)];
        }
        return $cases;
    }
}
