<?php
session_start();
include_once('../include/session.php');
require_once '../include/class.user.php';

// Create a debug log file
$debug_log = __DIR__ . '/pin_debug.txt';

if (!isset($_SESSION['uname'])) {
    file_put_contents($debug_log, date('Y-m-d H:i:s') . " - No session\n", FILE_APPEND);
    header("Location: login.php");
    exit();
}

$reg_user = new USER();
$stmt = $reg_user->runQuery("SELECT * FROM account WHERE uname=:uname");
$stmt->execute(array(":uname" => $_SESSION['uname']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);

file_put_contents($debug_log, date('Y-m-d H:i:s') . " - Page loaded for: " . $_SESSION['uname'] . "\n", FILE_APPEND);

if (isset($_POST['code'])) {
    file_put_contents($debug_log, date('Y-m-d H:i:s') . " - Form submitted\n", FILE_APPEND);
    
    $pin_auth = $row['pin_auth'];
    $sub = $_POST['pin_auth'];
    $uname = $_SESSION['uname'];
    
    file_put_contents($debug_log, date('Y-m-d H:i:s') . " - PIN from DB: $pin_auth, Entered: $sub\n", FILE_APPEND);
    
    if ($sub !== $pin_auth) {
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " - PIN mismatch\n", FILE_APPEND);
        header("Location: pin_auth_debug.php?errorpin");
        exit();
    } else {
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " - PIN matched, updating DB\n", FILE_APPEND);
        
        $sql = "UPDATE account SET pin_verify = '1' WHERE uname = :uname";
        $stmt_update = $reg_user->runQuery($sql);
        $stmt_update->execute(array(":uname" => $uname));
        
        file_put_contents($debug_log, date('Y-m-d H:i:s') . " - DB updated, about to redirect\n", FILE_APPEND);
        
        // Don't redirect, just show success
        die("SUCCESS! PIN verified. <a href='summary.php'>Click here to continue</a>");
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>PIN Debug</title>
</head>
<body>
    <h1>PIN Authentication Debug</h1>
    <?php if (isset($_GET['errorpin'])): ?>
        <p style="color:red;">Invalid PIN</p>
    <?php endif; ?>
    
    <p>User: <?php echo htmlspecialchars($row['fname']); ?></p>
    
    <form method="POST">
        <input type="password" name="pin_auth" placeholder="Enter PIN" required><br><br>
        <button type="submit" name="code">Submit</button>
    </form>
    
    <hr>
    <p><a href="pin_debug.txt">View Debug Log</a></p>
</body>
</html>
