<?php
ob_start(); // Start output buffering
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/print_header.php';

$database = new Database();
$db = $database->getConnection();
$auth = new Auth($database);
$error = null;
$success = null;

// Check permissions
if (!$auth->hasPermission('treasurer')) {
    header('Location: index.php');
    exit();
}

// Get current user ID
$currentUserId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

// Handle bank operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            if (!$currentUserId) {
                throw new Exception("يجب عليك تسجيل الدخول لإجراء هذه العملية");
            }

            switch ($_POST['action']) {
                case 'add_account':
                    $stmt = $db->prepare("INSERT INTO bank_accounts (bank_name, account_number, description) VALUES (?, ?, ?)");
                    $stmt->execute([
                        $_POST['bank_name'],
                        $_POST['account_number'],
                        $_POST['description']
                    ]);
                    $success = "تم إضافة الحساب البنكي بنجاح";
                    break;

                case 'delete_account':
                    // Delete all related transactions first
                    $db->beginTransaction();
                    try {
                        // Delete from financial_transactions
                        $stmt = $db->prepare("DELETE FROM financial_transactions WHERE (account_type = 'bank' AND account_id = ?) OR (transfer_to_type = 'bank' AND transfer_to_id = ?)");
                        $stmt->execute([$_POST['account_id'], $_POST['account_id']]);
                        
                        // Delete from bank_transactions
                        $stmt = $db->prepare("DELETE FROM bank_transactions WHERE account_id = ?");
                        $stmt->execute([$_POST['account_id']]);
                        
                        // Delete the account
                        $stmt = $db->prepare("DELETE FROM bank_accounts WHERE id = ?");
                        $stmt->execute([$_POST['account_id']]);
                        
                        $db->commit();
                        $success = "تم حذف الحساب البنكي وجميع عملياته بنجاح";
                        header("Location: index.php?page=bank_accounts");
                        exit;
                    } catch (Exception $e) {
                        $db->rollBack();
                        throw $e;
                    }

                case 'add_transaction':
                    $db->beginTransaction();
                    
                    // Add the transaction
                    $stmt = $db->prepare("INSERT INTO bank_transactions (account_id, type, amount, description, reference_number, transaction_date, created_by) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['account_id'],
                        $_POST['type'],
                        $_POST['amount'],
                        $_POST['description'],
                        $_POST['reference_number'],
                        $_POST['transaction_date'],
                        $currentUserId
                    ]);

                    // Update the balance of the account
                    $amount = $_POST['type'] === 'deposit' ? $_POST['amount'] : -$_POST['amount'];
                    $stmt = $db->prepare("UPDATE bank_accounts SET balance = balance + ? WHERE id = ?");
                    $stmt->execute([$amount, $_POST['account_id']]);

                    $db->commit();
                    break;

                case 'delete_transaction':
                    $db->beginTransaction();

                    // Get the transaction details
                    $stmt = $db->prepare("SELECT type, amount, account_id FROM bank_transactions WHERE id = ?");
                    $stmt->execute([$_POST['transaction_id']]);
                    $transaction = $stmt->fetch();

                    if ($transaction) {
                        // Reverse the effect of the transaction on the balance
                        $amount = $transaction['type'] === 'deposit' ? -$transaction['amount'] : $transaction['amount'];
                        $stmt = $db->prepare("UPDATE bank_accounts SET balance = balance + ? WHERE id = ?");
                        $stmt->execute([$amount, $transaction['account_id']]);

                        // Delete the transaction
                        $stmt = $db->prepare("DELETE FROM bank_transactions WHERE id = ?");
                        $stmt->execute([$_POST['transaction_id']]);
                    }

                    $db->commit();
                    break;
            }
            header('Location: index.php?page=bank_accounts&success=1');
            exit();
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $error = $e->getMessage();
        }
    }
}

// Handle delete account action
if (isset($_POST['action']) && $_POST['action'] === 'delete_account' && isset($_POST['account_id'])) {
    try {
        $db->beginTransaction();
        
        // Delete all related transactions first
        $stmt = $db->prepare("DELETE FROM financial_transactions WHERE (account_type = 'bank' AND account_id = ?) OR (transfer_to_type = 'bank' AND transfer_to_id = ?)");
        $stmt->execute([$_POST['account_id'], $_POST['account_id']]);
        
        // Delete from bank_transactions
        $stmt = $db->prepare("DELETE FROM bank_transactions WHERE account_id = ?");
        $stmt->execute([$_POST['account_id']]);
        
        // Delete the account
        $stmt = $db->prepare("DELETE FROM bank_accounts WHERE id = ?");
        $stmt->execute([$_POST['account_id']]);
        
        $db->commit();
        echo json_encode(['success' => true, 'message' => 'تم حذف الحساب وجميع عملياته بنجاح']);
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// Handle delete transaction action
if (isset($_POST['action']) && $_POST['action'] === 'delete_transaction' && isset($_POST['transaction_id'])) {
    try {
        $db->beginTransaction();

        // Get transaction details
        $stmt = $db->prepare("SELECT * FROM financial_transactions WHERE id = ? AND account_type = 'bank'");
        $stmt->execute([$_POST['transaction_id']]);
        $transaction = $stmt->fetch();

        if (!$transaction) {
            throw new Exception('العملية غير موجودة');
        }

        // Delete the transaction
        $stmt = $db->prepare("DELETE FROM financial_transactions WHERE id = ?");
        $stmt->execute([$_POST['transaction_id']]);

        $db->commit();
        echo json_encode(['success' => true, 'message' => 'تم حذف العملية بنجاح']);
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// Get bank accounts with their balances
$stmt = $db->query("
    SELECT ba.*,
           COALESCE(
               SUM(CASE 
                   WHEN bt.type = 'deposit' THEN bt.amount 
                   ELSE -bt.amount 
               END), 0
           ) + 
           COALESCE(
               SUM(CASE 
                   WHEN ft.type = 'income' AND ft.account_type = 'bank' THEN ft.amount 
                   WHEN ft.type = 'expense' AND ft.account_type = 'bank' THEN -ft.amount
                   WHEN ft.type = 'transfer' AND ft.account_type = 'bank' THEN -ft.amount
                   WHEN ft.type = 'transfer' AND ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba.id THEN ft.amount
                   ELSE 0 
               END), 0
           ) as current_balance,
           COUNT(DISTINCT bt.id) + 
           COUNT(DISTINCT CASE 
               WHEN ft.account_type = 'bank' OR 
                    (ft.type = 'transfer' AND ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba.id) 
               THEN ft.id 
           END) as transaction_count
    FROM bank_accounts ba
    LEFT JOIN bank_transactions bt ON ba.id = bt.account_id
    LEFT JOIN financial_transactions ft ON (ba.id = ft.account_id AND ft.account_type = 'bank') 
                                      OR (ft.type = 'transfer' AND ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba.id)
    GROUP BY ba.id
    ORDER BY ba.bank_name
");
$bankAccounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total balance
$totalBalance = array_sum(array_column($bankAccounts, 'current_balance'));

// Get recent transactions
$stmt = $db->query("
    SELECT 
        'bank' as source,
        bt.id as transaction_id,
        bt.transaction_date,
        bt.type,
        bt.amount,
        bt.description,
        bt.reference_number,
        ba.bank_name,
        ba.account_number,
        u.username as created_by_user,
        NULL as transfer_details
    FROM bank_transactions bt
    JOIN bank_accounts ba ON bt.account_id = ba.id
    LEFT JOIN users u ON bt.created_by = u.id
    
    UNION ALL
    
    SELECT 
        'finance' as source,
        ft.id as transaction_id,
        ft.transaction_date,
        CASE ft.type 
            WHEN 'income' THEN 'deposit'
            WHEN 'expense' THEN 'withdrawal'
            WHEN 'transfer' THEN 
                CASE 
                    WHEN ft.account_type = 'bank' THEN 'transfer_out'
                    WHEN ft.transfer_to_type = 'bank' THEN 'transfer_in'
                END
        END as type,
        ft.amount,
        ft.description,
        ft.payment_method as reference_number,
        ba.bank_name,
        ba.account_number,
        u.username as created_by_user,
        CASE ft.type 
            WHEN 'transfer' THEN 
                CASE 
                    WHEN ft.account_type = 'bank' THEN
                        CASE ft.transfer_to_type
                            WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = ft.transfer_to_id)
                            WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = ft.transfer_to_id)
                        END
                    WHEN ft.transfer_to_type = 'bank' THEN
                        CASE ft.account_type
                            WHEN 'bank' THEN (SELECT bank_name FROM bank_accounts WHERE id = ft.account_id)
                            WHEN 'cash' THEN (SELECT name FROM cash_funds WHERE id = ft.account_id)
                        END
                END
            ELSE NULL
        END as transfer_details
    FROM financial_transactions ft
    LEFT JOIN bank_accounts ba ON 
        (ft.account_type = 'bank' AND ft.account_id = ba.id) OR 
        (ft.type = 'transfer' AND ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba.id)
    LEFT JOIN users u ON ft.created_by = u.id
    WHERE ft.account_type = 'bank' OR (ft.type = 'transfer' AND ft.transfer_to_type = 'bank')
    
    ORDER BY 3 DESC, 2 DESC
    LIMIT 50
");
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get bank accounts for filter
$bankAccountsStmt = $db->prepare("SELECT id, bank_name FROM bank_accounts ORDER BY bank_name ASC");
$bankAccountsStmt->execute();
$bankAccountsFilter = $bankAccountsStmt->fetchAll();

// Get filter parameters
$selectedAccount = $_GET['account_id'] ?? 'all';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';

// Build query conditions
$conditions = [];
$params = [];

if ($selectedAccount !== 'all') {
    $conditions[] = "ft.account_id = ?";
    $params[] = $selectedAccount;
}

if ($startDate) {
    $conditions[] = "ft.transaction_date >= ?";
    $params[] = $startDate;
}

if ($endDate) {
    $conditions[] = "ft.transaction_date <= ?";
    $params[] = $endDate;
}

// Base query
$query = "
    SELECT 
        ft.*,
        ba.bank_name as account_name,
        ba_to.bank_name as transfer_to_name,
        cf.name as cash_fund_name,
        u.username as created_by_name,
        CASE 
            WHEN ft.type = 'income' THEN ic.name
            WHEN ft.type = 'expense' THEN ec.name
            ELSE NULL
        END as category_name
    FROM financial_transactions ft
    LEFT JOIN bank_accounts ba ON ft.account_type = 'bank' AND ft.account_id = ba.id
    LEFT JOIN bank_accounts ba_to ON ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba_to.id
    LEFT JOIN cash_funds cf ON (ft.transfer_to_type = 'cash' AND ft.transfer_to_id = cf.id) 
        OR (ft.account_type = 'cash' AND ft.account_id = cf.id)
    LEFT JOIN income_categories ic ON ft.type = 'income' AND ft.category_id = ic.id
    LEFT JOIN expense_categories ec ON ft.type = 'expense' AND ft.category_id = ec.id
    LEFT JOIN users u ON ft.created_by = u.id
    WHERE 1=1 ";

if (!empty($conditions)) {
    $query .= " AND " . implode(" AND ", $conditions);
}

$query .= " ORDER BY ft.transaction_date DESC, ft.id DESC";

// Get transactions
$stmt = $db->prepare($query);
$stmt->execute($params);
$transactionsFiltered = $stmt->fetchAll();

// Calculate totals for the filtered transactions
$totalsQuery = "
    SELECT 
        SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) as total_income,
        SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END) as total_expense,
        SUM(CASE 
            WHEN type = 'transfer' AND transfer_to_type IS NOT NULL THEN amount
            ELSE 0 
        END) as total_transfers_out,
        SUM(CASE 
            WHEN type = 'transfer' AND transfer_to_type IS NULL THEN amount
            ELSE 0 
        END) as total_transfers_in
    FROM financial_transactions ft
    WHERE 1=1 ";

if (!empty($conditions)) {
    $totalsQuery .= " AND " . implode(" AND ", $conditions);
}

$stmt = $db->prepare($totalsQuery);
$stmt->execute($params);
$totals = $stmt->fetch(PDO::FETCH_ASSOC);

$balance = $totals['total_income'] - $totals['total_expense'] + $totals['total_transfers_in'] - $totals['total_transfers_out'];

?>
<!-- Add DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.7.0/css/buttons.bootstrap5.min.css">

<!-- Add DataTables JS -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap5.min.js"></script>

<div class="container-fluid">
    <?php if ($error): ?>
    <div class="alert alert-danger">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
    <?php endif; ?>

    <!-- Financial Summary -->
    <div class="row mb-4">
        <div class="col-md-12 mb-3">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAccountModal">
                <i class="fas fa-plus"></i> إضافة حساب بنكي جديد
            </button>
        </div>
   
     
       
    </div>

    <!-- Bank Accounts Summary -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h5 class="card-title">الرصيد الإجمالي للحسابات البنكية</h5>
                    <h3 class="card-text"><?php echo number_format($totalBalance, 2); ?> درهم</h3>
                    <small>مجموع أرصدة <?php echo count($bankAccounts); ?> حساب</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Individual Bank Account Cards -->
     
    <div class="row mb-4">
        <?php foreach ($bankAccounts as $account): ?>
        <div class="col-md-4 mb-3">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h5 class="card-title"><?php echo htmlspecialchars($account['bank_name']); ?></h5>
                        <button class="btn btn-sm btn-outline-danger delete-account" 
                                data-id="<?php echo $account['id']; ?>"
                                data-name="<?php echo htmlspecialchars($account['bank_name']); ?>">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <p class="card-text">
                        <small class="text-muted"><?php echo htmlspecialchars($account['account_number']); ?></small>
                    </p>
                    <h2 class="card-text">
                        <span class="fs-4 <?php echo $account['current_balance'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($account['current_balance'], 2); ?> درهم
                        </span>
        </h2>
                    <div class="btn-group">
                  
                       
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Action Buttons -->
    <div class="row mb-4">
  
    </div>

    <!-- Filter Form -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3 align-items-end">
                <input type="hidden" name="page" value="bank_accounts">
                
                <div class="col-md-3">
                    <label for="account_id" class="form-label">الحساب البنكي</label>
                    <select name="account_id" id="account_id" class="form-select">
                        <option value="all" <?php echo $selectedAccount === 'all' ? 'selected' : ''; ?>>جميع الحسابات</option>
                        <?php foreach ($bankAccounts as $account): ?>
                            <option value="<?php echo $account['id']; ?>" <?php echo $selectedAccount == $account['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($account['bank_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label for="start_date" class="form-label">من تاريخ</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                </div>

                <div class="col-md-3">
                    <label for="end_date" class="form-label">إلى تاريخ</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                </div>

                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary">تصفية</button>
                    <a href="?page=bank_accounts" class="btn btn-secondary">إعادة تعيين</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="table-container">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">سجل العمليات</h4>
            <button onclick="window.print()" class="btn btn-secondary btn-sm">
                <i class="fas fa-print"></i> طباعة
            </button>
        </div>
        <table class="table table-striped datatable">
            <!-- Print Header -->
            <div class="d-none d-print-block mb-4">
                <?php echo get_print_header('سجل عمليات الحساب البنكي'); ?>
            </div>
            <thead>
                <tr>
                    <th>التاريخ</th>
                    <th>النوع</th>
                    <th>الوصف</th>
                    <th>المبلغ</th>
                    <th>طريقة الأداء</th>
                    <th>الحساب</th>
                    <th>المسجل</th>
                    <th>العمليات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactionsFiltered as $transaction): ?>
                <tr>
                    <td><?php echo date('Y-m-d', strtotime($transaction['transaction_date'])); ?></td>
                    <td>
                        <?php
                        switch($transaction['type']) {
                            case 'income':
                                echo '<span class="badge bg-success">مدخول</span>';
                                break;
                            case 'expense':
                                echo '<span class="badge bg-danger">مصروف</span>';
                                break;
                            case 'transfer':
                                if ($transaction['transfer_to_type']) {
                                    echo '<span class="badge bg-warning">تحويل صادر</span>';
                                } else {
                                    echo '<span class="badge bg-info">تحويل وارد</span>';
                                }
                                break;
                        }
                        ?>
                    </td>
                    <td><?php echo htmlspecialchars($transaction['description'] ?? ''); ?></td>
                    <td class="text-end">
                        <?php
                        $amountClass = '';
                        $prefix = '';
                        
                        switch($transaction['type']) {
                            case 'income':
                                $amountClass = 'text-success fw-bold';
                                $prefix = '+';
                                break;
                            case 'expense':
                                $amountClass = 'text-danger fw-bold';
                                $prefix = '-';
                                break;
                            case 'transfer':
                                if ($transaction['transfer_to_type']) {
                                    $amountClass = 'text-warning fw-bold';
                                    $prefix = '-';
                                } else {
                                    $amountClass = 'text-info fw-bold';
                                    $prefix = '+';
                                }
                                break;
                        }
                        
                        echo "<span class='$amountClass'>$prefix " . number_format($transaction['amount'], 2) . " درهم</span>";
                        ?>
                    </td>
                    <td><?php echo htmlspecialchars($transaction['payment_method'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($transaction['account_name'] ?? ''); ?></td>
                    <td><?php echo htmlspecialchars($transaction['created_by_name'] ?? ''); ?></td>
                    <td>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="delete_transaction">
                            <input type="hidden" name="transaction_id" value="<?php echo $transaction['id']; ?>">
                            <button type="submit" class="btn btn-sm btn-danger" 
                                    onclick="return confirm('هل أنت متأكد من حذف هذه المعاملة المالية؟');">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Print Styles -->
    <style media="print">
        @page {
            size: A4;
            margin: 1.5cm;
        }
        
        body {
            background: none !important;
        }
        
        .container-fluid {
            width: 100% !important;
            padding: 0 !important;
        }
        
        .card {
            border: none !important;
            box-shadow: none !important;
        }
        
        .card-header {
            display: none !important;
        }
        
        .btn, 
        .modal,
        .alert,
        form,
        .actions-column,
        .btn-close,
        .dataTables_wrapper .dataTables_filter,
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_paginate {
            display: none !important;
        }
        
        .table {
            width: 100% !important;
            margin-bottom: 0 !important;
            border-collapse: collapse !important;
        }
        
        .table th,
        .table td {
            padding: 8px !important;
            border: 1px solid #ddd !important;
            text-align: right !important;
        }
        
        .table thead th {
            background-color: #f8f9fa !important;
            border-bottom: 2px solid #ddd !important;
        }
        
        /* Show only date, amount and description columns when printing */
        .table th:not(:nth-child(1)):not(:nth-child(4)):not(:nth-child(3)),
        .table td:not(:nth-child(1)):not(:nth-child(4)):not(:nth-child(3)) {
            display: none !important;
        }
        
        /* Print header styles */
        .print-header {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .print-header img {
            max-width: 100%;
            height: auto;
        }
        
        .print-header h3 {
            margin: 10px 0;
            font-size: 20px;
        }
        
        .print-header p {
            margin: 5px 0;
            font-size: 14px;
        }
        
        .print-date {
            font-size: 12px;
            color: #666;
        }
        
        /* Hide account cards when printing */
        .row.mb-4 {
            display: none !important;
        }
    }
    </style>

    <!-- Print Script -->
    <script>
        function printTransactions() {
            window.print();
        }

        // Initialize DataTable with pagination
        $(document).ready(function() {
            $('#transactionsTable').DataTable({
                "pageLength": 25,
                "order": [[0, "desc"]],
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Arabic.json"
                },
                "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                       "<'row'<'col-sm-12'tr>>" +
                       "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
                "drawCallback": function(settings) {
                    // Re-initialize delete transaction handlers after page change
                    $('.delete-transaction').off('click').on('click', function(e) {
                        e.preventDefault();
                        const id = $(this).data('id');
                        
                        if (confirm('هل أنت متأكد من حذف هذه المعاملة المالية؟')) {
                            $.post('', {
                                action: 'delete_transaction',
                                transaction_id: id
                            }, function(response) {
                                const result = JSON.parse(response);
                                if (result.success) {
                                    location.reload();
                                } else {
                                    alert(result.message);
                                }
                            });
                        }
                    });
                }
            });
        });
    </script>

    <!-- Add Account Modal -->
    <div class="modal fade" id="addAccountModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">إضافة حساب بنكي جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_account">
                        <div class="mb-3">
                            <label class="form-label">اسم البنك</label>
                            <input type="text" class="form-control" name="bank_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">رقم الحساب</label>
                            <input type="text" class="form-control" name="account_number" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">الوصف</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-primary">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Deposit Modal -->
    <div class="modal fade" id="addDepositModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">إضافة إيداع جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_transaction">
                        <input type="hidden" name="type" value="deposit">
                        <div class="mb-3">
                            <label class="form-label">الحساب البنكي</label>
                            <select class="form-control" name="account_id" required>
                                <?php foreach ($bankAccounts as $account): ?>
                                <option value="<?php echo $account['id']; ?>">
                                    <?php echo htmlspecialchars($account['bank_name'] . ' - ' . $account['account_number']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">المبلغ</label>
                            <input type="number" step="0.01" class="form-control" name="amount" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">رقم المرجع</label>
                            <input type="text" class="form-control" name="reference_number">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">التاريخ</label>
                            <input type="date" class="form-control" name="transaction_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">الوصف</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-success">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Withdrawal Modal -->
    <div class="modal fade" id="addWithdrawalModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">إضافة سحب جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_transaction">
                        <input type="hidden" name="type" value="withdrawal">
                        <div class="mb-3">
                            <label class="form-label">الحساب البنكي</label>
                            <select class="form-control" name="account_id" required>
                                <?php foreach ($bankAccounts as $account): ?>
                                <option value="<?php echo $account['id']; ?>">
                                    <?php echo htmlspecialchars($account['bank_name'] . ' - ' . $account['account_number']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">المبلغ</label>
                            <input type="number" step="0.01" class="form-control" name="amount" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">رقم المرجع</label>
                            <input type="text" class="form-control" name="reference_number">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">التاريخ</label>
                            <input type="date" class="form-control" name="transaction_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">الوصف</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-danger">حفظ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function downloadStatement(id, type, name) {
            // Show date picker modal
            Swal.fire({
                title: 'تحديد فترة كشف الحساب',
                html: `
                    <div class="mb-3">
                        <label for="start_date" class="form-label">من تاريخ</label>
                        <input type="date" class="form-control" id="start_date" value="${new Date().toISOString().split('T')[0]}">
                    </div>
                    <div class="mb-3">
                        <label for="end_date" class="form-label">إلى تاريخ</label>
                        <input type="date" class="form-control" id="end_date" value="${new Date().toISOString().split('T')[0]}">
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'تحميل',
                cancelButtonText: 'إلغاء',
                preConfirm: () => {
                    const startDate = document.getElementById('start_date').value;
                    const endDate = document.getElementById('end_date').value;
                    
                    if (!startDate || !endDate) {
                        Swal.showValidationMessage('يرجى تحديد التاريخ');
                        return false;
                    }
                    
                    if (startDate > endDate) {
                        Swal.showValidationMessage('تاريخ البداية يجب أن يكون قبل تاريخ النهاية');
                        return false;
                    }
                    
                    return { startDate, endDate };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const url = `index.php?page=download_statement&id=${id}&type=${type}&start_date=${result.value.startDate}&end_date=${result.value.endDate}`;
                    window.location.href = url;
                }
            });
        }

        $(document).ready(function() {
            // Delete account handler
            $('.delete-account').click(function(e) {
                e.preventDefault();
                const id = $(this).data('id');
                
                if (confirm('هل أنت متأكد من حذف الحساب البنكي؟')) {
                    $.post('index.php?page=bank_accounts', {
                        action: 'delete_account',
                        account_id: id
                    }).done(function(response) {
                        window.location.reload();
                    }).fail(function() {
                        alert('حدث خطأ أثناء الحذف');
                    });
                }
            });

            // Delete transaction handler
            $('.delete-transaction').click(function(e) {
                e.preventDefault();
                const id = $(this).data('id');
                
                if (confirm('هل أنت متأكد من حذف العملية؟')) {
                    $.post('index.php?page=bank_accounts', {
                        action: 'delete_transaction',
                        transaction_id: id
                    }).done(function(response) {
                        window.location.reload();
                    }).fail(function() {
                        alert('حدث خطأ أثناء الحذف');
                    });
                }
            });
        });
    </script>
