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

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

$vendor_id = $_SESSION['vendor_id'];
$account_id = isset($_GET['id']) ? $_GET['id'] : '';

if (empty($account_id)) {
    header("Location: bank-account.php");
    exit();
}

// List of supported Nigerian banks
$supportedBanks = [
    'Access Bank', 'First Bank', 'GTBank', 
    'UBA', 'Zenith Bank', 'Fidelity Bank',
    'Union Bank', 'Stanbic IBTC', 'Ecobank'
];

// Fetch bank account details
require_once '../config/conn.php'; // Fixed path
$stmt = $conn->prepare("SELECT * FROM vendor_bank_accounts WHERE id = ? AND vendor_id = ?");
$stmt->bind_param("ss", $account_id, $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
$account = $result->fetch_assoc();

if (!$account) {
    header("Location: bank-account.php");
    exit();
}
?>

<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold">Edit Bank Account</h1>
        <button onclick="window.location.href='bank-account.php'" class="text-gray-500 hover:text-gray-700">
            <i class="fas fa-arrow-left mr-1"></i> Back
        </button>
    </div>

    <div id="messageContainer" class="mb-4"></div>

    <div class="bg-white rounded-lg shadow p-6">
        <form id="bankAccountForm">
            <input type="hidden" name="account_id" value="<?= htmlspecialchars($account['id']) ?>">
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Bank Name</label>
                <select name="bank_name" id="bankName" class="w-full px-3 py-2 border rounded-md" required>
                    <option value="">Select Bank</option>
                    <?php foreach ($supportedBanks as $bank): ?>
                        <option value="<?= htmlspecialchars($bank) ?>" <?= $account['bank_name'] == $bank ? 'selected' : '' ?>>
                            <?= htmlspecialchars($bank) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <p id="bankError" class="text-red-500 text-xs mt-1 hidden"></p>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Account Name</label>
                <input type="text" name="account_name" id="accountName" class="w-full px-3 py-2 border rounded-md" required
                       pattern="[a-zA-Z ]{3,}" title="Letters only, at least 3 characters"
                       value="<?= htmlspecialchars($account['account_name']) ?>">
                <p id="nameError" class="text-red-500 text-xs mt-1 hidden"></p>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">Account Number (10 digits)</label>
                <input type="text" name="account_number" id="accountNumber" class="w-full px-3 py-2 border rounded-md" required
                       pattern="\d{10}" title="Exactly 10 digits"
                       value="<?= htmlspecialchars($account['account_number']) ?>">
                <p id="numberError" class="text-red-500 text-xs mt-1 hidden"></p>
            </div>
            
            <div class="flex justify-end space-x-3">
                <button type="button" onclick="window.location.href='bank-account.php'" class="px-4 py-2 border rounded-md">
                    Cancel
                </button>
                <button type="submit" id="submitBtn" class="px-4 py-2 bg-primary-500 text-white rounded-md">
                    Update
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Handle form submission
document.getElementById('bankAccountForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = document.getElementById('submitBtn');
    const originalBtnText = submitBtn.innerHTML;
    
    // Show loading state
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
    submitBtn.disabled = true;
    
    // Clear errors
    document.querySelectorAll('[id$="Error"]').forEach(el => {
        el.classList.add('hidden');
    });
    
    // Client-side validation
    let isValid = true;
    const requiredFields = ['bank_name', 'account_name', 'account_number'];
    
    requiredFields.forEach(field => {
        const input = document.querySelector(`[name="${field}"]`);
        if (!input.value.trim()) {
            const errorElement = document.getElementById(`${field}Error`);
            if (errorElement) {
                errorElement.textContent = 'This field is required';
                errorElement.classList.remove('hidden');
            }
            isValid = false;
        }
    });
    
    if (!isValid) {
        submitBtn.innerHTML = originalBtnText;
        submitBtn.disabled = false;
        showMessage('error', 'Please fill all required fields');
        return;
    }
    
    fetch('ajax/update_bank_account.php', { // Fixed path
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showMessage('success', data.message);
            setTimeout(() => {
                window.location.href = 'bank-account.php';
            }, 1500);
        } else {
            if (data.errors) {
                // Display field errors
                Object.entries(data.errors).forEach(([field, error]) => {
                    const errorElement = document.getElementById(`${field}Error`);
                    if (errorElement) {
                        errorElement.textContent = error;
                        errorElement.classList.remove('hidden');
                    }
                });
            }
            showMessage('error', data.message || 'Failed to update account');
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        showMessage('error', 'Network error. Please check your connection and try again.');
    })
    .finally(() => {
        submitBtn.innerHTML = originalBtnText;
        submitBtn.disabled = false;
    });
});

// Show message
function showMessage(type, message) {
    const messageContainer = document.getElementById('messageContainer');
    const alertClass = type === 'success' ? 
        'bg-green-100 border-green-400 text-green-700' : 
        'bg-red-100 border-red-400 text-red-700';
    
    messageContainer.innerHTML = `
        <div class="border ${alertClass} px-4 py-3 rounded">
            ${message}
        </div>
    `;
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        messageContainer.innerHTML = '';
    }, 5000);
}
</script>

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