<?php
ob_start();
include 'include/header.php';
require_once '../config/conn.php';

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

$student_id = $_SESSION['user_id'];

// Check if user has a PIN
$pin_stmt = $conn->prepare("SELECT id FROM wallet_pins WHERE student_id = ?");
$pin_stmt->bind_param("i", $student_id);
$pin_stmt->execute();
$has_pin = $pin_stmt->get_result()->num_rows > 0;
?>

<div class="max-w-md mx-auto">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <svg class="w-8 h-8 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
            </svg>
        </div>
        <h2 class="text-1xl font-bold">Transaction PIN</h2>
        <p class="text-gray-500 mt-2">
            <?= $has_pin ? 'Update your 4-digit transaction PIN' : 'Create a 4-digit transaction PIN' ?>
        </p>
    </div>

    <form id="pinForm" class="space-y-4">
        <input type="hidden" name="student_id" value="<?= $student_id ?>">
        <input type="hidden" name="action" value="<?= $has_pin ? 'update' : 'create' ?>">
        
        <?php if ($has_pin): ?>
            <div>
                <label class="block text-gray-700 mb-1">Current PIN</label>
                <input type="password" name="current_pin" maxlength="4" inputmode="numeric" pattern="\d{4}"
                       class="w-full px-3 py-2 border rounded-lg" placeholder="Enter current PIN" required>
            </div>
        <?php endif; ?>
        
        <div>
            <label class="block text-gray-700 mb-1">New PIN (4 digits)</label>
            <input type="password" name="new_pin" id="newPin" maxlength="4" inputmode="numeric" pattern="\d{4}"
                   class="w-full px-3 py-2 border rounded-lg" placeholder="Enter new PIN" required>
        </div>
        
        <div>
            <label class="block text-gray-700 mb-1">Confirm New PIN</label>
            <input type="password" name="confirm_pin" id="confirmPin" maxlength="4" inputmode="numeric" pattern="\d{4}"
                   class="w-full px-3 py-2 border rounded-lg" placeholder="Confirm new PIN" required>
        </div>
        
        <div class="pt-2">
            <button type="submit" class="w-full bg-primary-500 text-white py-2 px-4 rounded-lg hover:bg-primary-600 transition">
                <?= $has_pin ? 'Update PIN' : 'Set PIN' ?>
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const pinForm = document.getElementById('pinForm');
    
    pinForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(pinForm);
        const newPin = formData.get('new_pin');
        const confirmPin = formData.get('confirm_pin');
        
        // Validate PINs
        if (newPin.length !== 4 || !/^\d+$/.test(newPin)) {
            alert('PIN must be exactly 4 digits');
            return;
        }
        
        if (newPin !== confirmPin) {
            alert('PINs do not match');
            return;
        }
        
        // Submit via AJAX
        fetch('process_pin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                window.location.href = 'wallet.php';
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please check console for details.');
        });
    });
});
</script>

<?php include 'include/footer.php'; ?>