<?php
require_once 'admin_config.php';
requireAdminLogin();

// Get current bank details
$stmt = $pdo->query("SELECT * FROM bank_details WHERE id = 1");
$bank = $stmt->fetch();

// If no bank details exist, create default
if (!$bank) {
    $stmt = $pdo->prepare("INSERT INTO bank_details (bank_name, account_name, account_number, sort_code, swift_code, iban, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute(['First National Bank', 'EliteEquip Ltd', '1234567890', '12-34-56', 'FNBNUS33', 'US12ABCD1234567890', 1]);
    $stmt = $pdo->query("SELECT * FROM bank_details WHERE id = 1");
    $bank = $stmt->fetch();
}

$success = '';
$error = '';

// Update bank details
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bank_name = trim($_POST['bank_name']);
    $account_name = trim($_POST['account_name']);
    $account_number = trim($_POST['account_number']);
    $sort_code = trim($_POST['sort_code']);
    $swift_code = trim($_POST['swift_code']);
    $iban = trim($_POST['iban']);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    if (empty($bank_name) || empty($account_name) || empty($account_number)) {
        $error = 'Bank Name, Account Name, and Account Number are required!';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE bank_details SET bank_name = ?, account_name = ?, account_number = ?, sort_code = ?, swift_code = ?, iban = ?, is_active = ? WHERE id = 1");
            $stmt->execute([$bank_name, $account_name, $account_number, $sort_code, $swift_code, $iban, $is_active]);
            $success = 'Bank details updated successfully!';
            
            // Refresh data
            $stmt = $pdo->query("SELECT * FROM bank_details WHERE id = 1");
            $bank = $stmt->fetch();
        } catch(PDOException $e) {
            $error = 'Error updating bank details: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bank Details - EliteEquip Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="admin_style.css" rel="stylesheet">
    <style>
        .bank-form-container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .bank-preview {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            padding: 20px;
            border-radius: 16px;
            margin-bottom: 30px;
        }
        
        .bank-preview h4 {
            font-size: 1rem;
            font-weight: 700;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .bank-preview-content {
            background: white;
            padding: 15px;
            border-radius: 12px;
            font-size: 0.85rem;
        }
        
        .bank-preview-content p {
            margin: 5px 0;
            font-family: monospace;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 10px;
        }
        
        .checkbox-group input {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        .checkbox-group label {
            margin: 0;
            cursor: pointer;
        }
        
        .alert {
            padding: 12px 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
    </style>
</head>
<body>
<div class="admin-container">
    <?php include 'sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'topbar.php'; ?>
        
        <div class="bank-form-container">
            <div class="form-container">
                <h2 style="margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-university" style="color: var(--secondary);"></i>
                    Bank Account Details
                </h2>
                <p style="color: var(--text-gray); margin-bottom: 25px;">These bank details will appear on customer invoices for payment</p>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Live Preview -->
                <div class="bank-preview">
                    <h4>
                        <i class="fas fa-eye"></i> 
                        Live Preview (How it appears on invoice)
                    </h4>
                    <div class="bank-preview-content" id="livePreview">
                        <p><strong>Bank:</strong> <?php echo htmlspecialchars($bank['bank_name']); ?></p>
                        <p><strong>Account Name:</strong> <?php echo htmlspecialchars($bank['account_name']); ?></p>
                        <p><strong>Account Number:</strong> <?php echo htmlspecialchars($bank['account_number']); ?></p>
                        <?php if (!empty($bank['sort_code'])): ?>
                        <p><strong>Sort Code:</strong> <?php echo htmlspecialchars($bank['sort_code']); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($bank['swift_code'])): ?>
                        <p><strong>SWIFT Code:</strong> <?php echo htmlspecialchars($bank['swift_code']); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($bank['iban'])): ?>
                        <p><strong>IBAN:</strong> <?php echo htmlspecialchars($bank['iban']); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Edit Form -->
                <form method="POST" id="bankForm">
                    <div class="form-group">
                        <label>Bank Name *</label>
                        <input type="text" name="bank_name" class="form-control" value="<?php echo htmlspecialchars($bank['bank_name']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Account Name *</label>
                        <input type="text" name="account_name" class="form-control" value="<?php echo htmlspecialchars($bank['account_name']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Account Number *</label>
                        <input type="text" name="account_number" class="form-control" value="<?php echo htmlspecialchars($bank['account_number']); ?>" required>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Sort Code</label>
                            <input type="text" name="sort_code" class="form-control" value="<?php echo htmlspecialchars($bank['sort_code']); ?>" placeholder="00-00-00">
                        </div>
                        
                        <div class="form-group">
                            <label>SWIFT Code</label>
                            <input type="text" name="swift_code" class="form-control" value="<?php echo htmlspecialchars($bank['swift_code']); ?>" placeholder="XXXXXXXX">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>IBAN</label>
                        <input type="text" name="iban" class="form-control" value="<?php echo htmlspecialchars($bank['iban']); ?>" placeholder="IBAN Number">
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" name="is_active" id="is_active" value="1" <?php echo $bank['is_active'] ? 'checked' : ''; ?>>
                        <label for="is_active">Active (Show on invoices)</label>
                    </div>
                    
                    <div style="display: flex; gap: 10px; margin-top: 25px;">
                        <button type="submit" class="btn-primary">
                            <i class="fas fa-save"></i> Update Bank Details
                        </button>
                        <button type="button" class="btn-warning" onclick="resetForm()">
                            <i class="fas fa-undo"></i> Reset
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Live preview update
const form = document.getElementById('bankForm');
const inputs = form.querySelectorAll('input[name], textarea[name]');
const preview = document.getElementById('livePreview');

function updatePreview() {
    const bankName = document.querySelector('input[name="bank_name"]')?.value || '';
    const accountName = document.querySelector('input[name="account_name"]')?.value || '';
    const accountNumber = document.querySelector('input[name="account_number"]')?.value || '';
    const sortCode = document.querySelector('input[name="sort_code"]')?.value || '';
    const swiftCode = document.querySelector('input[name="swift_code"]')?.value || '';
    const iban = document.querySelector('input[name="iban"]')?.value || '';
    
    let html = `
        <p><strong>Bank:</strong> ${bankName || 'Not set'}</p>
        <p><strong>Account Name:</strong> ${accountName || 'Not set'}</p>
        <p><strong>Account Number:</strong> ${accountNumber || 'Not set'}</p>
    `;
    
    if (sortCode) html += `<p><strong>Sort Code:</strong> ${sortCode}</p>`;
    if (swiftCode) html += `<p><strong>SWIFT Code:</strong> ${swiftCode}</p>`;
    if (iban) html += `<p><strong>IBAN:</strong> ${iban}</p>`;
    
    preview.innerHTML = html;
}

// Add event listeners to all inputs
inputs.forEach(input => {
    if (input.type !== 'checkbox') {
        input.addEventListener('input', updatePreview);
    }
});

// Reset form to original values
function resetForm() {
    const originalValues = {
        bank_name: '<?php echo htmlspecialchars($bank['bank_name']); ?>',
        account_name: '<?php echo htmlspecialchars($bank['account_name']); ?>',
        account_number: '<?php echo htmlspecialchars($bank['account_number']); ?>',
        sort_code: '<?php echo htmlspecialchars($bank['sort_code']); ?>',
        swift_code: '<?php echo htmlspecialchars($bank['swift_code']); ?>',
        iban: '<?php echo htmlspecialchars($bank['iban']); ?>'
    };
    
    for (const [key, value] of Object.entries(originalValues)) {
        const input = document.querySelector(`input[name="${key}"]`);
        if (input) input.value = value;
    }
    
    updatePreview();
    showToast('Form reset to original values', 'info');
}

function showToast(message, type) {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: ${type === 'info' ? '#3b82f6' : '#10b981'};
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
    `;
    toast.innerHTML = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

// Add animation style
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
`;
document.head.appendChild(style);
</script>
</body>
</html>