<?php
/**
 * SMM Paket Satış Scripti - Banka Hesapları Yönetimi
 * @version 1.0.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// Banka logoları
$bankLogos = [
    'ziraat' => ['name' => 'Ziraat Bankası', 'color' => '#006341', 'icon' => '🏦'],
    'garanti' => ['name' => 'Garanti BBVA', 'color' => '#00854a', 'icon' => '💚'],
    'is' => ['name' => 'İş Bankası', 'color' => '#003399', 'icon' => '💙'],
    'yapi_kredi' => ['name' => 'Yapı Kredi', 'color' => '#004990', 'icon' => '🔵'],
    'akbank' => ['name' => 'Akbank', 'color' => '#e30613', 'icon' => '❤️'],
    'halkbank' => ['name' => 'Halkbank', 'color' => '#00529b', 'icon' => '🏛️'],
    'vakifbank' => ['name' => 'VakıfBank', 'color' => '#00427a', 'icon' => '🏢'],
    'denizbank' => ['name' => 'Denizbank', 'color' => '#004e8c', 'icon' => '🌊'],
    'teb' => ['name' => 'TEB', 'color' => '#00a0df', 'icon' => '💎'],
    'ing' => ['name' => 'ING Bank', 'color' => '#ff6200', 'icon' => '🧡'],
    'qnb' => ['name' => 'QNB Finansbank', 'color' => '#5c068c', 'icon' => '💜'],
    'enpara' => ['name' => 'Enpara', 'color' => '#ff6600', 'icon' => '🔶'],
    'papara' => ['name' => 'Papara', 'color' => '#6c3eb8', 'icon' => '🟣'],
    'tosla' => ['name' => 'Tosla', 'color' => '#00c853', 'icon' => '💚'],
    'ininal' => ['name' => 'İninal', 'color' => '#ff5722', 'icon' => '🟠'],
    'diger' => ['name' => 'Diğer', 'color' => '#64748b', 'icon' => '🏦']
];

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/banka-hesaplari.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add_bank':
                $bankName = trim($_POST['bank_name'] ?? '');
                $accountHolder = trim($_POST['account_holder'] ?? '');
                $iban = trim($_POST['iban'] ?? '');
                $branchCode = trim($_POST['branch_code'] ?? '');
                $accountNumber = trim($_POST['account_number'] ?? '');
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                
                if (empty($bankName) || empty($accountHolder) || empty($iban)) {
                    throw new Exception('Banka adı, hesap sahibi ve IBAN zorunludur.');
                }
                
                // IBAN formatı kontrolü
                $iban = strtoupper(str_replace(' ', '', $iban));
                if (!preg_match('/^TR[0-9]{24}$/', $iban)) {
                    throw new Exception('Geçerli bir IBAN girin. (TR ile başlamalı, 26 karakter olmalı)');
                }
                
                // IBAN formatla
                $ibanFormatted = implode(' ', str_split($iban, 4));
                
                $stmt = $db->prepare("
                    INSERT INTO bank_accounts (bank_name, account_holder, iban, branch_code, account_number, is_active, sort_order, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$bankName, $accountHolder, $ibanFormatted, $branchCode, $accountNumber, $isActive, $sortOrder]);
                
                setFlash('success', 'Banka hesabı başarıyla eklendi.');
                break;
                
            case 'update_bank':
                $bankId = (int)($_POST['bank_id'] ?? 0);
                $bankName = trim($_POST['bank_name'] ?? '');
                $accountHolder = trim($_POST['account_holder'] ?? '');
                $iban = trim($_POST['iban'] ?? '');
                $branchCode = trim($_POST['branch_code'] ?? '');
                $accountNumber = trim($_POST['account_number'] ?? '');
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                
                if ($bankId <= 0) {
                    throw new Exception('Geçersiz hesap.');
                }
                
                if (empty($bankName) || empty($accountHolder) || empty($iban)) {
                    throw new Exception('Banka adı, hesap sahibi ve IBAN zorunludur.');
                }
                
                // IBAN formatı kontrolü
                $iban = strtoupper(str_replace(' ', '', $iban));
                if (!preg_match('/^TR[0-9]{24}$/', $iban)) {
                    throw new Exception('Geçerli bir IBAN girin. (TR ile başlamalı, 26 karakter olmalı)');
                }
                
                $ibanFormatted = implode(' ', str_split($iban, 4));
                
                $stmt = $db->prepare("
                    UPDATE bank_accounts 
                    SET bank_name = ?, account_holder = ?, iban = ?, branch_code = ?, account_number = ?, is_active = ?, sort_order = ?
                    WHERE id = ?
                ");
                $stmt->execute([$bankName, $accountHolder, $ibanFormatted, $branchCode, $accountNumber, $isActive, $sortOrder, $bankId]);
                
                setFlash('success', 'Banka hesabı güncellendi.');
                break;
                
            case 'delete_bank':
                $bankId = (int)($_POST['bank_id'] ?? 0);
                
                if ($bankId <= 0) {
                    throw new Exception('Geçersiz hesap.');
                }
                
                $db->prepare("DELETE FROM bank_accounts WHERE id = ?")->execute([$bankId]);
                
                setFlash('success', 'Banka hesabı silindi.');
                break;
                
            case 'toggle_status':
                $bankId = (int)($_POST['bank_id'] ?? 0);
                $isActive = (int)($_POST['is_active'] ?? 0);
                
                if ($bankId <= 0) {
                    throw new Exception('Geçersiz hesap.');
                }
                
                $db->prepare("UPDATE bank_accounts SET is_active = ? WHERE id = ?")->execute([$isActive, $bankId]);
                
                setFlash('success', 'Hesap durumu güncellendi.');
                break;
                
            case 'update_order':
                $orders = $_POST['orders'] ?? [];
                
                if (is_array($orders)) {
                    $stmt = $db->prepare("UPDATE bank_accounts SET sort_order = ? WHERE id = ?");
                    foreach ($orders as $id => $order) {
                        $stmt->execute([(int)$order, (int)$id]);
                    }
                }
                
                setFlash('success', 'Sıralama güncellendi.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/banka-hesaplari.php');
    exit;
}

// Banka hesaplarını çek
try {
    $bankAccounts = $db->query("SELECT * FROM bank_accounts ORDER BY sort_order ASC, id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $bankAccounts = [];
}

// İstatistikler
$stats = [
    'total' => count($bankAccounts),
    'active' => count(array_filter($bankAccounts, fn($b) => $b['is_active'] == 1)),
    'inactive' => count(array_filter($bankAccounts, fn($b) => $b['is_active'] == 0))
];

$adminPageTitle = 'Banka Hesapları';
require_once __DIR__ . '/header.php';
?>

<style>
/* Header */
.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.page-header h2 {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header h2 i {
    color: var(--primary);
}

/* Stats */
.stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    text-align: center;
}

.stat-card .value {
    font-size: 32px;
    font-weight: 800;
    margin-bottom: 5px;
}

.stat-card .label {
    font-size: 13px;
    color: var(--text-secondary);
}

/* Bank Cards Grid */
.banks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.bank-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s;
    position: relative;
}

.bank-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.2);
    border-color: rgba(var(--primary-rgb), 0.3);
}

.bank-card.inactive {
    opacity: 0.6;
}

.bank-card-header {
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border-bottom: 1px solid var(--border-color);
}

.bank-icon {
    width: 56px;
    height: 56px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    flex-shrink: 0;
}

.bank-info {
    flex: 1;
    min-width: 0;
}

.bank-name {
    font-size: 18px;
    font-weight: 700;
    margin: 0 0 4px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.bank-holder {
    font-size: 13px;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.bank-status {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.bank-status.active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.bank-status.inactive {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.bank-card-body {
    padding: 20px;
}

.iban-box {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 15px;
    position: relative;
}

.iban-label {
    font-size: 10px;
    text-transform: uppercase;
    color: var(--text-secondary);
    letter-spacing: 0.5px;
    margin-bottom: 8px;
}

.iban-value {
    font-family: 'Courier New', monospace;
    font-size: 15px;
    font-weight: 600;
    letter-spacing: 1px;
    color: var(--primary);
    word-break: break-all;
}

.copy-btn {
    position: absolute;
    top: 12px;
    right: 12px;
    background: rgba(var(--primary-rgb), 0.15);
    border: none;
    color: var(--primary);
    width: 32px;
    height: 32px;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.copy-btn:hover {
    background: var(--primary);
    color: #fff;
}

.bank-details {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

.bank-detail {
    background: var(--bg-hover);
    padding: 12px;
    border-radius: 8px;
}

.bank-detail label {
    display: block;
    font-size: 10px;
    text-transform: uppercase;
    color: var(--text-secondary);
    margin-bottom: 4px;
}

.bank-detail span {
    font-size: 13px;
    font-weight: 500;
}

.bank-card-footer {
    padding: 15px 20px;
    background: var(--bg-hover);
    display: flex;
    gap: 10px;
    border-top: 1px solid var(--border-color);
}

.bank-card-footer .btn {
    flex: 1;
    padding: 10px;
    border: none;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.2s;
}

.btn-edit {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.btn-edit:hover {
    background: #3b82f6;
    color: #fff;
}

.btn-toggle {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.btn-toggle:hover {
    background: #f59e0b;
    color: #fff;
}

.btn-delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.btn-delete:hover {
    background: #ef4444;
    color: #fff;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 80px 20px;
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
}

.empty-state i {
    font-size: 60px;
    color: var(--primary);
    opacity: 0.3;
    margin-bottom: 20px;
}

.empty-state h3 {
    font-size: 20px;
    margin-bottom: 10px;
}

.empty-state p {
    color: var(--text-secondary);
    margin-bottom: 25px;
}

/* Modal */
.modal-content {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    color: var(--text-primary);
}

.modal-header {
    border-bottom: 1px solid var(--border-color);
    padding: 20px 24px;
}

.modal-title {
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}

.modal-title i {
    color: var(--primary);
}

.modal-body {
    padding: 24px;
}

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 16px 24px;
    gap: 10px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.form-label {
    display: block;
    font-weight: 500;
    margin-bottom: 8px;
    font-size: 14px;
}

.form-label .required {
    color: #ef4444;
}

.form-control {
    width: 100%;
    padding: 12px 15px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.2s;
}

.form-control:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
    outline: none;
}

.form-control::placeholder {
    color: var(--text-secondary);
}

.form-hint {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 6px;
}

.form-check {
    display: flex;
    align-items: center;
    gap: 10px;
}

.form-check input[type="checkbox"] {
    width: 20px;
    height: 20px;
    accent-color: var(--primary);
}

.form-check label {
    font-size: 14px;
    cursor: pointer;
}

/* Bank Select */
.bank-select-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin-bottom: 20px;
}

.bank-select-item {
    padding: 12px;
    background: var(--bg-hover);
    border: 2px solid var(--border-color);
    border-radius: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
}

.bank-select-item:hover {
    border-color: var(--primary);
}

.bank-select-item.selected {
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.1);
}

.bank-select-item .icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.bank-select-item .name {
    font-size: 11px;
    color: var(--text-secondary);
}

/* Info Box */
.info-box {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 10px;
    padding: 15px;
    font-size: 13px;
    color: #3b82f6;
    display: flex;
    align-items: flex-start;
    gap: 10px;
}

.info-box i {
    margin-top: 2px;
}

/* Responsive */
@media (max-width: 768px) {
    .banks-grid {
        grid-template-columns: 1fr;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .bank-select-grid {
        grid-template-columns: repeat(3, 1fr);
    }
    
    .bank-details {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 480px) {
    .bank-select-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .bank-card-footer {
        flex-wrap: wrap;
    }
    
    .bank-card-footer .btn {
        min-width: calc(50% - 5px);
    }
}
</style>

<div class="page-header">
    <h2><i class="fas fa-university"></i> Banka Hesapları</h2>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addBankModal">
        <i class="fas fa-plus"></i> Yeni Hesap Ekle
    </button>
</div>

<!-- Stats -->
<div class="stats-row">
    <div class="stat-card">
        <div class="value" style="color: var(--primary)"><?php echo $stats['total']; ?></div>
        <div class="label">Toplam Hesap</div>
    </div>
    <div class="stat-card">
        <div class="value" style="color: #10b981"><?php echo $stats['active']; ?></div>
        <div class="label">Aktif Hesap</div>
    </div>
    <div class="stat-card">
        <div class="value" style="color: #ef4444"><?php echo $stats['inactive']; ?></div>
        <div class="label">Pasif Hesap</div>
    </div>
</div>

<?php if (empty($bankAccounts)): ?>
<!-- Empty State -->
<div class="empty-state">
    <i class="fas fa-university"></i>
    <h3>Henüz banka hesabı eklenmemiş</h3>
    <p>Müşterilerinizin ödeme yapabilmesi için banka hesabı ekleyin.</p>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addBankModal">
        <i class="fas fa-plus me-2"></i> İlk Hesabı Ekle
    </button>
</div>
<?php else: ?>
<!-- Bank Cards -->
<div class="banks-grid">
    <?php foreach ($bankAccounts as $bank): 
        // Banka rengini belirle
        $bankKey = 'diger';
        $bankNameLower = mb_strtolower($bank['bank_name']);
        foreach ($bankLogos as $key => $logo) {
            if (strpos($bankNameLower, mb_strtolower($logo['name'])) !== false || strpos($bankNameLower, $key) !== false) {
                $bankKey = $key;
                break;
            }
        }
        $bankColor = $bankLogos[$bankKey]['color'];
        $bankIcon = $bankLogos[$bankKey]['icon'];
    ?>
    <div class="bank-card <?php echo !$bank['is_active'] ? 'inactive' : ''; ?>">
        <div class="bank-card-header">
            <div class="bank-icon" style="background: <?php echo $bankColor; ?>20; color: <?php echo $bankColor; ?>">
                <?php echo $bankIcon; ?>
            </div>
            <div class="bank-info">
                <h3 class="bank-name">
                    <?php echo clean($bank['bank_name']); ?>
                </h3>
                <div class="bank-holder"><?php echo clean($bank['account_holder']); ?></div>
            </div>
            <span class="bank-status <?php echo $bank['is_active'] ? 'active' : 'inactive'; ?>">
                <?php echo $bank['is_active'] ? 'Aktif' : 'Pasif'; ?>
            </span>
        </div>
        
        <div class="bank-card-body">
            <div class="iban-box">
                <div class="iban-label">IBAN</div>
                <div class="iban-value" id="iban-<?php echo $bank['id']; ?>"><?php echo clean($bank['iban']); ?></div>
                <button class="copy-btn" onclick="copyIban(<?php echo $bank['id']; ?>)" title="Kopyala">
                    <i class="fas fa-copy"></i>
                </button>
            </div>
            
            <?php if ($bank['branch_code'] || $bank['account_number']): ?>
            <div class="bank-details">
                <?php if ($bank['branch_code']): ?>
                <div class="bank-detail">
                    <label>Şube Kodu</label>
                    <span><?php echo clean($bank['branch_code']); ?></span>
                </div>
                <?php endif; ?>
                <?php if ($bank['account_number']): ?>
                <div class="bank-detail">
                    <label>Hesap No</label>
                    <span><?php echo clean($bank['account_number']); ?></span>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="bank-card-footer">
            <button class="btn btn-edit" onclick="editBank(<?php echo htmlspecialchars(json_encode($bank)); ?>)">
                <i class="fas fa-edit"></i> Düzenle
            </button>
            <form method="POST" style="flex: 1; display: contents;">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="toggle_status">
                <input type="hidden" name="bank_id" value="<?php echo $bank['id']; ?>">
                <input type="hidden" name="is_active" value="<?php echo $bank['is_active'] ? 0 : 1; ?>">
                <button type="submit" class="btn btn-toggle">
                    <i class="fas fa-<?php echo $bank['is_active'] ? 'pause' : 'play'; ?>"></i>
                    <?php echo $bank['is_active'] ? 'Pasif Yap' : 'Aktif Yap'; ?>
                </button>
            </form>
            <button class="btn btn-delete" onclick="deleteBank(<?php echo $bank['id']; ?>, '<?php echo clean($bank['bank_name']); ?>')">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Add Bank Modal -->
<div class="modal fade" id="addBankModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add_bank">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle"></i> Yeni Banka Hesabı</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                
                <div class="modal-body">
                    <!-- Hızlı Banka Seçimi -->
                    <div class="form-group">
                        <label class="form-label">Hızlı Banka Seçimi</label>
                        <div class="bank-select-grid">
                            <?php foreach (array_slice($bankLogos, 0, 12) as $key => $logo): ?>
                            <div class="bank-select-item" onclick="selectBank('<?php echo $logo['name']; ?>', this)">
                                <div class="icon"><?php echo $logo['icon']; ?></div>
                                <div class="name"><?php echo $logo['name']; ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Banka Adı <span class="required">*</span></label>
                            <input type="text" name="bank_name" id="addBankName" class="form-control" placeholder="Örn: Ziraat Bankası" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Hesap Sahibi <span class="required">*</span></label>
                            <input type="text" name="account_holder" class="form-control" placeholder="Ad Soyad veya Şirket Adı" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">IBAN <span class="required">*</span></label>
                        <input type="text" name="iban" class="form-control" placeholder="TR00 0000 0000 0000 0000 0000 00" required maxlength="32">
                        <div class="form-hint">TR ile başlayan 26 karakterlik IBAN numaranızı girin</div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Şube Kodu</label>
                            <input type="text" name="branch_code" class="form-control" placeholder="Örn: 1234">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Hesap Numarası</label>
                            <input type="text" name="account_number" class="form-control" placeholder="Örn: 12345678">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Sıralama</label>
                            <input type="number" name="sort_order" class="form-control" value="0" min="0">
                            <div class="form-hint">Küçük değerler önce gösterilir</div>
                        </div>
                        <div class="form-group" style="display: flex; align-items: flex-end; padding-bottom: 8px;">
                            <div class="form-check">
                                <input type="checkbox" name="is_active" id="addIsActive" checked>
                                <label for="addIsActive">Aktif (Müşterilere göster)</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="info-box">
                        <i class="fas fa-info-circle"></i>
                        <div>Eklediğiniz banka hesapları, müşterilerin ödeme sayfasında görüntülenecektir. Sadece aktif hesaplar gösterilir.</div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-plus"></i> Hesap Ekle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Bank Modal -->
<div class="modal fade" id="editBankModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update_bank">
                <input type="hidden" name="bank_id" id="editBankId">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Banka Hesabı Düzenle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Banka Adı <span class="required">*</span></label>
                            <input type="text" name="bank_name" id="editBankName" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Hesap Sahibi <span class="required">*</span></label>
                            <input type="text" name="account_holder" id="editAccountHolder" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">IBAN <span class="required">*</span></label>
                        <input type="text" name="iban" id="editIban" class="form-control" required maxlength="32">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Şube Kodu</label>
                            <input type="text" name="branch_code" id="editBranchCode" class="form-control">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Hesap Numarası</label>
                            <input type="text" name="account_number" id="editAccountNumber" class="form-control">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Sıralama</label>
                            <input type="number" name="sort_order" id="editSortOrder" class="form-control" min="0">
                        </div>
                        <div class="form-group" style="display: flex; align-items: flex-end; padding-bottom: 8px;">
                            <div class="form-check">
                                <input type="checkbox" name="is_active" id="editIsActive">
                                <label for="editIsActive">Aktif (Müşterilere göster)</label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-save"></i> Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';

// Banka seçimi
function selectBank(name, element) {
    document.querySelectorAll('.bank-select-item').forEach(function(item) {
        item.classList.remove('selected');
    });
    element.classList.add('selected');
    document.getElementById('addBankName').value = name;
}

// IBAN kopyala
function copyIban(bankId) {
    var ibanElement = document.getElementById('iban-' + bankId);
    var iban = ibanElement.textContent.replace(/\s/g, '');
    
    navigator.clipboard.writeText(iban).then(function() {
        Swal.fire({
            icon: 'success',
            title: 'Kopyalandı!',
            text: 'IBAN panoya kopyalandı.',
            timer: 1500,
            showConfirmButton: false,
            background: '#1e293b',
            color: '#f8fafc'
        });
    }).catch(function() {
        // Fallback
        var textArea = document.createElement('textarea');
        textArea.value = iban;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        
        Swal.fire({
            icon: 'success',
            title: 'Kopyalandı!',
            text: 'IBAN panoya kopyalandı.',
            timer: 1500,
            showConfirmButton: false,
            background: '#1e293b',
            color: '#f8fafc'
        });
    });
}

// Banka düzenle
function editBank(bank) {
    document.getElementById('editBankId').value = bank.id;
    document.getElementById('editBankName').value = bank.bank_name;
    document.getElementById('editAccountHolder').value = bank.account_holder;
    document.getElementById('editIban').value = bank.iban;
    document.getElementById('editBranchCode').value = bank.branch_code || '';
    document.getElementById('editAccountNumber').value = bank.account_number || '';
    document.getElementById('editSortOrder').value = bank.sort_order || 0;
    document.getElementById('editIsActive').checked = bank.is_active == 1;
    
    new bootstrap.Modal(document.getElementById('editBankModal')).show();
}

// Banka sil
function deleteBank(bankId, bankName) {
    Swal.fire({
        title: 'Banka Hesabını Sil',
        html: '<strong>' + bankName + '</strong> hesabı silinecek.<br><small class="text-muted">Bu işlem geri alınamaz!</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-trash me-1"></i> Evet, Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="delete_bank">' +
                '<input type="hidden" name="bank_id" value="' + bankId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// IBAN formatla (input sırasında)
document.querySelectorAll('input[name="iban"]').forEach(function(input) {
    input.addEventListener('input', function(e) {
        var value = e.target.value.replace(/\s/g, '').toUpperCase();
        if (value.length > 26) value = value.substring(0, 26);
        
        // TR ile başlamasını sağla
        if (value.length >= 2 && value.substring(0, 2) !== 'TR') {
            if (value.substring(0, 2).match(/[0-9]/)) {
                value = 'TR' + value;
            }
        }
        
        // 4'erli grupla
        var formatted = value.match(/.{1,4}/g);
        e.target.value = formatted ? formatted.join(' ') : value;
    });
});
</script>

<?php require_once __DIR__ . '/footer.php'; ?>