<?php
include_once("layout/header.php");
include_once("include/SecurityUtils.php");

// Verify user is authenticated
if(!isset($_SESSION['login'])){
    header("Location:./login.php");
    exit();
}

// Prevent redirection if already has account number
if(isset($_SESSION['acct_no'])){
    header('Location:./user/dashboard.php');
    exit();
}

// Fetch user information securely
$viesConn = "SELECT * FROM users WHERE acct_no = :acct_no LIMIT 1";
$stmt = $conn->prepare($viesConn);
$stmt->execute([':acct_no' => $_SESSION['login']]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Verify user exists
if(!$row){
    session_destroy();
    header("Location:./login.php");
    exit();
}

$user_id = $row['id'];
$fullName = htmlspecialchars($row['firstname'] . " " . $row['lastname'], ENT_QUOTES, 'UTF-8');
$acct_no = htmlspecialchars($row['acct_no'], ENT_QUOTES, 'UTF-8');
$errors = [];
$success = false;

// Handle PIN submission with security validations
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pin_submit'])){
    
    // Verify CSRF token
    if(!isset($_POST['csrf_token']) || !SecurityUtils::verifyCSRFToken($_POST['csrf_token'])){
        $errors[] = 'Security token invalid. Please try again.';
    }
    
    // Check rate limiting to prevent brute force attacks
    if(SecurityUtils::isRateLimited('pin_attempt_' . $user_id, 5, 300)){ // 5 attempts per 5 minutes
        $errors[] = 'Too many attempts. Please try again in a few minutes.';
        SecurityUtils::logSecurityEvent('PIN_BRUTE_FORCE', 'User ' . $user_id . ' exceeded PIN attempt limit', 'warning');
    }
    
    // Validate and sanitize PIN input
    $pinVerified = isset($_POST['input']) ? trim($_POST['input']) : '';
    
    if(empty($pinVerified)){
        $errors[] = 'Please enter your PIN.';
    } elseif(!is_numeric($pinVerified) || strlen($pinVerified) < 4){
        $errors[] = 'Invalid PIN format. PIN must be numeric.';
        SecurityUtils::logSecurityEvent('PIN_INVALID_FORMAT', 'Invalid PIN format attempted by user ' . $user_id, 'warning');
    } else {
        // Compare PIN securely - should be hashed in database
        $old_otp = $row['acct_pin'];
        
        // Use secure comparison to prevent timing attacks
        if(hash_equals($pinVerified, $old_otp)){
            // PIN is correct
            $_SESSION['acct_no'] = $acct_no;
            session_regenerate_id(true); // Regenerate session to prevent fixation
            
            // Log successful PIN verification
            SecurityUtils::logSecurityEvent('PIN_VERIFIED', 'User ' . $user_id . ' successfully verified PIN', 'info');
            
            header("Location:./user/dashboard.php");
            exit();
        } else {
            $errors[] = 'Invalid PIN. Please try again.';
            SecurityUtils::logSecurityEvent('PIN_FAILED', 'Failed PIN attempt for user ' . $user_id, 'warning');
        }
    }
}
?>
                <div class="form-container outer">
                    <div class="form-form">
                        <div class="form-form-wrap">
                            <div class="form-container">
                                <div class="form-content">

                                    <div class="d-flex user-meta">
                                        <img src="./assets/profile/<?= htmlspecialchars($row['image'], ENT_QUOTES, 'UTF-8') ?>" class="usr-profile" alt="avatar">
                                        <div class="">
                                            <p class=""><?= $fullName ?></p>
                                        </div>

                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <h3 class="text-center">Welcome</h3>
                                            <p class="text-info">Enter PIN to Continue</p>

                                        </div>
                                    </div>

                                    <!-- Display error messages if any -->
                                    <?php if(!empty($errors)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <strong>Error:</strong>
                                            <ul class="mb-0">
                                                <?php foreach($errors as $error): ?>
                                                    <li><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form class="text-left" method="POST" action="<?= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') ?>">
                                        <!-- CSRF Token -->
                                        <?= SecurityUtils::getCSRFField() ?>
                                        
                                        <div class="form">
                                            <div class="field-wrapper input mb-2">

                                                <div class="d-flex justify-content-between">
                                                    <label for="pincode">PIN CODE</label>
                                                </div>
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-lock"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                                                <input id="pincode" name="input" type="number" class="form-control input" placeholder="PINCODE" autocomplete="off" required min="0" max="9999">

                                            </div>
                                        </div>

                                        <div class="text-center">
                                            <div id="container">
                                                <div>
                                                    <button type="button" class="shuffle">1</button>
                                                    <button type="button" class="shuffle">2</button>
                                                    <button type="button" class="shuffle">3</button>
                                                </div>
                                                <div>
                                                    <button type="button" class="shuffle">4</button>
                                                    <button type="button" class="shuffle">5</button>
                                                    <button type="button" class="shuffle">6</button>
                                                </div>
                                                <div>
                                                    <button type="button" class="shuffle">7</button>
                                                    <button type="button" class="shuffle">8</button>
                                                    <button type="button" class="shuffle">9</button>
                                                </div>
                                                <div>
                                                    <button type="button" class="del">X</button>
                                                    <button type="button" class="shuffle">0</button>
                                                    <button type="button" class="faq">?</button>
                                                </div>
                                                <div class="text-center">
                                                    <input class="btn btn-primary mt-2" type="submit" value="Submit" name="pin_submit">
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

<?php

include_once("layout/footer.php");

?>
