<?php
session_start();
require_once 'config/database.php';

// Function to get setting from admin settings table
function get_admin_setting($pdo, $key, $default = null) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        if ($row && !empty($row['setting_value'])) return $row['setting_value'];
    } catch (Exception $e) {
        // ignore
    }
    return $default;
}

echo "<h2>Fee Access Test</h2>\n";

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    echo "<p>ERROR: User not logged in or insufficient permissions</p>\n";
    exit();
} else {
    echo "<p>✓ User is logged in with role: " . $_SESSION['user_role'] . "</p>\n";
}

// Check if fee password is set and verify it
$fee_password_verified = false;
$fee_password_hash = get_admin_setting($pdo, 'fee_password');

echo "<p>Fee password hash in database: " . ($fee_password_hash ? "SET" : "NOT SET") . "</p>\n";

// If no fee password is set, allow access
if (empty($fee_password_hash)) {
    $fee_password_verified = true;
    echo "<p>✓ No fee password set, access granted</p>\n";
} else {
    // Check if password is already verified in session
    if (!empty($_SESSION['fee_password_verified']) && $_SESSION['fee_password_verified'] === true) {
        $fee_password_verified = true;
        echo "<p>✓ Fee password already verified in session</p>\n";
    } else if (!empty($_POST['fee_access_password'])) {
        if (password_verify($_POST['fee_access_password'], $fee_password_hash)) {
            $_SESSION['fee_password_verified'] = true;
            $fee_password_verified = true;
            echo "<p>✓ Fee password verified successfully</p>\n";
        } else {
            echo "<p>✗ Fee password verification failed</p>\n";
        }
    } else {
        // If fee password is set but not verified, show password form
        $fee_password_verified = false;
        echo "<p>ℹ Fee password required but not yet verified</p>\n";
    }
}

echo "<p>Final access status: " . ($fee_password_verified ? "GRANTED" : "DENIED") . "</p>\n";

// Show session data
echo "<h3>Session Data:</h3>\n";
echo "<pre>" . print_r($_SESSION, true) . "</pre>\n";

// Show form if needed
if (!$fee_password_verified) {
    echo "<h3>Fee Access Form:</h3>\n";
    echo "<form method='POST' action=''>\n";
    echo "  <input type='password' name='fee_access_password' placeholder='Enter fee password'>\n";
    echo "  <input type='submit' value='Verify'>\n";
    echo "</form>\n";
} else {
    echo "<p><a href='fees/student_fees.php'>Go to Fee Collection</a></p>\n";
}
?>