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

if (!isset($_SESSION['uname'])) {
    header("Location: login.php");
    exit();
}

if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == $url) {
    header('Location: logout.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);

if (isset($_POST['code'])) {
    $pin_auth = $row['pin_auth'];
    $sub = $_POST['pin_auth'];
    $uname = $_SESSION['uname'];
    
    if ($sub !== $pin_auth) {
        header("Location: pin_auth_clean.php?errorpin");
        exit();
    } else {
        // PIN matched - skip the pin_verify update for now
        // $sql = "UPDATE account SET pin_verify = '1' WHERE uname = :uname";
        // $stmt_update = $reg_user->runQuery($sql);
        // $stmt_update->execute(array(":uname" => $uname));
        
        header("Location: summary.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PIN Authentication</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>PIN Authentication Test</h1>
    <?php if (isset($_GET['errorpin'])): ?>
        <p style="color:red;">Invalid PIN. Please try again.</p>
    <?php endif; ?>
    
    <p>Welcome <?php echo htmlspecialchars($row['fname']); ?>!</p>
    
    <form method="POST">
        <label>Enter your PIN:</label><br>
        <input type="password" name="pin_auth" required><br><br>
        <button type="submit" name="code">Submit</button>
    </form>
</body>
</html>
