<?php
include 'include/header.php';

if (!isset($_SESSION['vendor_id']) || empty($_SESSION['vendor_id'])) {
    header("Location: vendor-login.php");
    exit();
}
$vendor_id = $_SESSION['vendor_id'];

// Handle PIN submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pin = $_POST['pin'];
    $confirm_pin = $_POST['confirm_pin'];
    
    if ($pin !== $confirm_pin) {
        $error = "PINs do not match";
    } elseif (strlen($pin) !== 6 || !ctype_digit($pin)) {
        $error = "PIN must be 6 digits";
    } else {
        // Hash the PIN
        $hashed_pin = password_hash($pin, PASSWORD_DEFAULT);
        
        // Update in database
        $stmt = $conn->prepare("UPDATE vendors SET withdrawal_pin = ? WHERE id = ?");
        $stmt->bind_param("ss", $hashed_pin, $vendor_id);
        
        if ($stmt->execute()) {
            $success = "Withdrawal PIN set successfully";
        } else {
            $error = "Error setting PIN: " . $conn->error;
        }
    }
}

// Check if PIN exists
$has_pin = false;
$stmt = $conn->prepare("SELECT withdrawal_pin FROM vendors WHERE id = ?");
$stmt->bind_param("s", $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $has_pin = !empty($row['withdrawal_pin']);
}
?>

<div class="container mx-auto px-4 py-8 max-w-md">
    <h1 class="text-2xl font-bold mb-6"><?= $has_pin ? 'Change' : 'Set' ?> Withdrawal PIN</h1>
    
    <?php if (isset($success)): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <?= $success ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            <?= $error ?>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-lg shadow p-6">
        <form method="POST">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">New 6-digit PIN</label>
                <input type="password" name="pin" maxlength="6" pattern="\d{6}" 
                       class="w-full px-3 py-2 border rounded-md" required>
            </div>
            
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-1">Confirm PIN</label>
                <input type="password" name="confirm_pin" maxlength="6" pattern="\d{6}" 
                       class="w-full px-3 py-2 border rounded-md" required>
            </div>
            
            <button type="submit" class="w-full bg-primary-500 text-white py-2 rounded-md">
                <?= $has_pin ? 'Change PIN' : 'Set PIN' ?>
            </button>
        </form>
    </div>
</div>

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