<?php
/**
 * Verify user account PIN before allowing transfer to proceed.
 * Called via AJAX from the transfer-page PIN modal.
 * 
 * Returns:
 *   "success"  — PIN correct, transfer may proceed
 *   "invalid"  — PIN incorrect
 *   "locked"   — account locked/suspended
 *   "error"    — missing data or session
 */
session_start();
include "../../connect/db.php";

// Must be logged in
if (!isset($_SESSION['chap'])) {
    echo "error";
    exit;
}

// Must have POST data
if (!isset($_POST['pin'])) {
    echo "error";
    exit;
}

$email = $_SESSION['chap'];
$pin   = trim($_POST['pin']);

// Validate PIN format — must be exactly 4 digits
if (!preg_match('/^\d{4}$/', $pin)) {
    echo "invalid";
    exit;
}

// Fetch user's PIN from database using prepared statement
$stmt = $con->prepare("SELECT pincode, status FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "error";
    exit;
}

$row = $result->fetch_assoc();
$stmt->close();

// Check account status
if ($row['status'] === 'suspended' || $row['status'] === 'terminated') {
    echo "locked";
    exit;
}

// Verify PIN — plaintext comparison (matches current database schema)
if ($pin === $row['pincode']) {
    echo "success";
} else {
    echo "invalid";
}
?>
