<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'] ?? 'guest';
$user_name = $_SESSION['username'] ?? 'Unknown';

// Get system name for branding
$system_name = get_system_name($pdo);

// Handle form submissions
$message = '';
$message_type = '';

// Edit bank account - load data
$edit_account = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM bank_accounts WHERE id = ?");
        $stmt->execute([$id]);
        $edit_account = $stmt->fetch();
        if (!$edit_account) {
            $message = 'ব্যাংক অ্যাকাউন্ট খুঁজে পাওয়া যায়নি!';
            $message_type = 'danger';
        }
    } catch (Exception $e) {
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Update bank account
if (isset($_POST['update_bank'])) {
    $id = (int)$_POST['edit_id'];
    $bank_name = trim($_POST['bank_name']);
    $branch_name = trim($_POST['branch']);
    $account_number = trim($_POST['account_no']);
    $account_name = trim($_POST['account_name']);
    
    if (!empty($bank_name) && !empty($branch_name) && !empty($account_number) && !empty($account_name)) {
        try {
            $stmt = $pdo->prepare("UPDATE bank_accounts SET bank_name = ?, branch_name = ?, account_number = ?, account_name = ? WHERE id = ?");
            $stmt->execute([$bank_name, $branch_name, $account_number, $account_name, $id]);
            $message = 'ব্যাংক অ্যাকাউন্ট সফলভাবে আপডেট করা হয়েছে!';
            $message_type = 'success';
            // Redirect to prevent form resubmission
            header('Location: bank_accounts.php?msg=' . urlencode($message) . '&type=' . $message_type);
            exit();
        } catch (Exception $e) {
            $message = 'ত্রুটি: ' . $e->getMessage();
            $message_type = 'danger';
        }
    } else {
        $message = 'সব ফিল্ড পূরণ করুন!';
        $message_type = 'warning';
    }
}

// Add new bank account
else if (isset($_POST['add_bank'])) {
    $bank_name = trim($_POST['bank_name']);
    $branch_name = trim($_POST['branch']);
    $account_number = trim($_POST['account_no']);
    $account_name = trim($_POST['account_name']);
    
    if (!empty($bank_name) && !empty($branch_name) && !empty($account_number) && !empty($account_name)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO bank_accounts (bank_name, branch_name, account_number, account_name) VALUES (?, ?, ?, ?)");
            $stmt->execute([$bank_name, $branch_name, $account_number, $account_name]);
            $message = 'ব্যাংক অ্যাকাউন্ট সফলভাবে যোগ করা হয়েছে!';
            $message_type = 'success';
            // Redirect to prevent form resubmission
            header('Location: bank_accounts.php?msg=' . urlencode($message) . '&type=' . $message_type);
            exit();
        } catch (Exception $e) {
            $message = 'ত্রুটি: ' . $e->getMessage();
            $message_type = 'danger';
        }
    } else {
        $message = 'সব ফিল্ড পূরণ করুন!';
        $message_type = 'warning';
    }
}

// Check for message from redirect
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
    $message_type = isset($_GET['type']) ? $_GET['type'] : 'info';
}

// Delete bank account
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM bank_accounts WHERE id = ?");
        $stmt->execute([$id]);
        $message = 'ব্যাংক অ্যাকাউন্ট সফলভাবে মুছে ফেলা হয়েছে!';
        $message_type = 'success';
        // Redirect to prevent accidental deletion on refresh
        header('Location: bank_accounts.php?msg=' . urlencode($message) . '&type=' . $message_type);
        exit();
    } catch (Exception $e) {
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Fetch all bank accounts
try {
    $stmt = $pdo->query("SELECT * FROM bank_accounts ORDER BY bank_name, branch_name");
    $bank_accounts = $stmt->fetchAll();
} catch (Exception $e) {
    $bank_accounts = [];
    $message = 'ত্রুটি: ' . $e->getMessage();
    $message_type = 'danger';
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ব্যাংক অ্যাকাউন্ট ম্যানেজমেন্ট - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            border-radius: 0.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }
        .table th {
            font-weight: 600;
        }
        .btn-action {
            margin-right: 5px;
        }
        .action-cell {
            white-space: nowrap;
        }
        .form-control, .form-select {
            border-radius: 0.375rem;
        }
        .btn {
            border-radius: 0.375rem;
        }
        .navbar {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
    </style>
</head>
<body>
    <header class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand">ব্যাংক অ্যাকাউন্ট ম্যানেজমেন্ট</span>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php"><i class="fas fa-home"></i> হোম</a>
                <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
            </div>
        </div>
    </header>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-md-12">
            <h3><i class="fas fa-university"></i> ব্যাংক অ্যাকাউন্ট ম্যানেজমেন্ট</h3>
            
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <!-- Add/Edit Bank Account Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-<?php echo isset($edit_account) ? 'edit' : 'plus-circle'; ?>"></i> 
                        <?php echo isset($edit_account) ? 'ব্যাংক অ্যাকাউন্ট সম্পাদনা করুন' : 'নতুন ব্যাংক অ্যাকাউন্ট যোগ করুন'; ?>
                    </h5>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <?php if (isset($edit_account)): ?>
                            <input type="hidden" name="edit_id" value="<?php echo htmlspecialchars($edit_account['id']); ?>">
                        <?php endif; ?>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="bank_name" class="form-label">ব্যাংকের নাম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="bank_name" name="bank_name" 
                                       value="<?php echo isset($edit_account) ? htmlspecialchars($edit_account['bank_name']) : ''; ?>" required>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="branch" class="form-label">ব্রাঞ্চ <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="branch" name="branch" 
                                       value="<?php echo isset($edit_account) ? htmlspecialchars($edit_account['branch_name']) : ''; ?>" required>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="account_no" class="form-label">অ্যাকাউন্ট নম্বর <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="account_no" name="account_no" 
                                       value="<?php echo isset($edit_account) ? htmlspecialchars($edit_account['account_number']) : ''; ?>" required>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="account_name" class="form-label">অ্যাকাউন্ট নাম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="account_name" name="account_name" 
                                       value="<?php echo isset($edit_account) ? htmlspecialchars($edit_account['account_name']) : ''; ?>" required>
                            </div>
                        </div>
                        <button type="submit" name="<?php echo isset($edit_account) ? 'update_bank' : 'add_bank'; ?>" class="btn btn-primary">
                            <i class="fas fa-<?php echo isset($edit_account) ? 'sync' : 'save'; ?>"></i> 
                            <?php echo isset($edit_account) ? 'আপডেট করুন' : 'সেভ করুন'; ?>
                        </button>
                        <?php if (isset($edit_account)): ?>
                            <a href="bank_accounts.php" class="btn btn-secondary"><i class="fas fa-times"></i> বাতিল</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
            
            <!-- Bank Accounts List -->
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-list"></i> ব্যাংক অ্যাকাউন্ট তালিকা</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($bank_accounts)): ?>
                        <div class="alert alert-info">কোন ব্যাংক অ্যাকাউন্ট পাওয়া যায়নি।</div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>#</th>
                                        <th>ব্যাংকের নাম</th>
                                        <th>ব্রাঞ্চ</th>
                                        <th>অ্যাকাউন্ট নম্বর</th>
                                        <th>অ্যাকাউন্ট নাম</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($bank_accounts as $index => $account): ?>
                                        <tr>
                                            <td><?php echo $index + 1; ?></td>
                                            <td><?php echo htmlspecialchars($account['bank_name']); ?></td>
                                            <td><?php echo htmlspecialchars($account['branch_name']); ?></td>
                                            <td><?php echo htmlspecialchars($account['account_number']); ?></td>
                                            <td><?php echo htmlspecialchars($account['account_name']); ?></td>
                                            <td class="action-cell">
                                                <a href="?edit=<?php echo $account['id']; ?>" 
                                                   class="btn btn-success btn-sm btn-action" 
                                                   title="সম্পাদনা">
                                                    <i class="fas fa-edit"></i> সম্পাদনা
                                                </a>
                                                <a href="?delete=<?php echo $account['id']; ?>" 
                                                   class="btn btn-danger btn-sm" 
                                                   onclick="return confirm('আপনি কি নিশ্চিত যে এই ব্যাংক অ্যাকাউন্ট মুছে ফেলতে চান?')">
                                                    <i class="fas fa-trash"></i> মুছুন
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>