<?php
include '../include/config.php';

echo "<h2>PIN Debug Information</h2>";

// Check if column exists
$check = $conn->query("SHOW COLUMNS FROM patients LIKE 'login_pin'");
if($check->num_rows > 0) {
    echo "✅ login_pin column exists<br><br>";
} else {
    echo "❌ login_pin column missing - run: ALTER TABLE patients ADD COLUMN login_pin VARCHAR(10);<br><br>";
}

// Show all patients with their PINs
$result = $conn->query("SELECT patient_id, first_name, last_name, login_pin, portal_active FROM patients LIMIT 10");

echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Patient ID</th><th>Name</th><th>PIN in DB</th><th>Expected PIN (first 4 of ID)</th><th>Active</th></tr>";

while($row = $result->fetch_assoc()) {
    $expected_pin = substr($row['patient_id'], 0, 4);
    echo "<tr>";
    echo "<td>" . $row['patient_id'] . "</td>";
    echo "<td>" . $row['first_name'] . " " . $row['last_name'] . "</td>";
    echo "<td style='color:" . ($row['login_pin'] == $expected_pin ? 'green' : 'red') . "'>" . ($row['login_pin'] ?? 'NULL') . "</td>";
    echo "<td>" . $expected_pin . "</td>";
    echo "<td>" . ($row['portal_active'] ? 'Yes' : 'No') . "</td>";
    echo "</tr>";
}
echo "</table>";

// Test specific PIN
$test_pin = '2025';
echo "<br><h3>Testing PIN: $test_pin</h3>";

$test = $conn->query("SELECT patient_id, first_name, last_name FROM patients WHERE patient_id LIKE '$test_pin%' OR login_pin = '$test_pin'");
if($test->num_rows > 0) {
    while($t = $test->fetch_assoc()) {
        echo "✅ PIN $test_pin matches patient: " . $t['first_name'] . " " . $t['last_name'] . " (ID: " . $t['patient_id'] . ")<br>";
    }
} else {
    echo "❌ No patient found with PIN: $test_pin<br>";
}
?>