<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';

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

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

// Handle financial transactions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            switch ($_POST['action']) {
                case 'add_transaction':
                    $db->beginTransaction();
                    try {
                        // Insert the transaction
                        $stmt = $db->prepare("INSERT INTO financial_transactions (type, category_id, amount, description, transaction_date, payment_method, account_type, account_id, created_by) 
                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $_POST['type'],
                            $_POST['category_id'],
                            $_POST['amount'],
                            $_POST['description'],
                            $_POST['transaction_date'],
                            $_POST['payment_method'],
                            $_POST['account_type'],
                            $_POST['account_id'],
                            $_SESSION['user_id']
                        ]);
                        
                        // Update account/fund balance
                        // For income: add to balance
                        // For expense: subtract from balance
                        $amount = $_POST['type'] === 'income' ? $_POST['amount'] : -$_POST['amount'];
                        $table = $_POST['account_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                        
                        $stmt = $db->prepare("UPDATE $table SET balance = balance + ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                        $stmt->execute([$amount, $_POST['account_id']]);
                        
                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        throw $e;
                    }
                    break;

                case 'delete_transaction':
                    if (isset($_POST['transaction_id']) && !empty($_POST['transaction_id'])) {
                        $db->beginTransaction();
                        try {
                            // Get transaction details before deletion
                            $stmt = $db->prepare("SELECT * FROM financial_transactions WHERE id = ?");
                            $stmt->execute([$_POST['transaction_id']]);
                            $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
                            
                            if ($transaction) {
                                // Calculate the amount to adjust the balance
                                $adjustmentAmount = 0;
                                
                                if ($transaction['type'] === 'income') {
                                    // If deleting income, subtract the amount
                                    $adjustmentAmount = -$transaction['amount'];
                                } elseif ($transaction['type'] === 'expense') {
                                    // If deleting expense, add the amount back
                                    $adjustmentAmount = $transaction['amount'];
                                } elseif ($transaction['type'] === 'transfer') {
                                    // If deleting transfer, reverse both sides
                                    // Add back to source account
                                    $sourceTable = $transaction['account_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                                    $stmt = $db->prepare("UPDATE $sourceTable SET balance = balance + ? WHERE id = ?");
                                    $stmt->execute([$transaction['amount'], $transaction['account_id']]);
                                    
                                    // Subtract from destination account
                                    $destTable = $transaction['transfer_to_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                                    $stmt = $db->prepare("UPDATE $destTable SET balance = balance - ? WHERE id = ?");
                                    $stmt->execute([$transaction['amount'], $transaction['transfer_to_id']]);
                                }
                                
                                // Update the balance if it's not a transfer
                                if ($transaction['type'] !== 'transfer' && $adjustmentAmount != 0) {
                                    $table = $transaction['account_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                                    $stmt = $db->prepare("UPDATE $table SET balance = balance + ? WHERE id = ?");
                                    $stmt->execute([$adjustmentAmount, $transaction['account_id']]);
                                }
                            }
                            
                            // Delete the transaction
                            $stmt = $db->prepare("DELETE FROM financial_transactions WHERE id = ?");
                            $stmt->execute([$_POST['transaction_id']]);
                            
                            $db->commit();
                        } catch (Exception $e) {
                            $db->rollBack();
                            throw $e;
                        }
                    }
                    break;

                case 'transfer_funds':
                    $db->beginTransaction();
                    try {
                        // Record the transfer transaction first
                        $stmt = $db->prepare("INSERT INTO financial_transactions (type, amount, description, transaction_date, 
                                            account_type, account_id, transfer_to_type, transfer_to_id, created_by) 
                                            VALUES ('transfer', ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $_POST['amount'],
                            $_POST['description'],
                            $_POST['transaction_date'],
                            $_POST['source_type'],
                            $_POST['source_id'],
                            $_POST['destination_type'],
                            $_POST['destination_id'],
                            $_SESSION['user_id']
                        ]);

                        // Subtract from source account/fund
                        $sourceTable = $_POST['source_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                        $stmt = $db->prepare("UPDATE $sourceTable SET balance = balance - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                        $stmt->execute([$_POST['amount'], $_POST['source_id']]);

                        // Add to destination account/fund
                        $destTable = $_POST['destination_type'] === 'bank' ? 'bank_accounts' : 'cash_funds';
                        $stmt = $db->prepare("UPDATE $destTable SET balance = balance + ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                        $stmt->execute([$_POST['amount'], $_POST['destination_id']]);

                        $db->commit();
                    } catch (Exception $e) {
                        $db->rollBack();
                        throw $e;
                    }
                    break;

                case 'add_category':
                    $table = $_POST['category_type'] === 'income' ? 'income_categories' : 'expense_categories';
                    $stmt = $db->prepare("INSERT INTO $table (name, description) VALUES (?, ?)");
                    $stmt->execute([$_POST['name'], $_POST['description']]);
                    break;

                case 'delete_category':
                    $table = $_POST['category_type'] === 'income' ? 'income_categories' : 'expense_categories';
                    if (isset($_POST['category_id']) && !empty($_POST['category_id'])) {
                        // Vérifier si la catégorie est utilisée
                        $stmt = $db->prepare("SELECT COUNT(*) as count FROM financial_transactions WHERE category_id = ?");
                        $stmt->execute([$_POST['category_id']]);
                        $result = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($result['count'] > 0) {
                            throw new Exception("لا يمكن حذف هذا التصنيف لأنه مستخدم في معاملات مالية");
                        }
                        
                        $stmt = $db->prepare("DELETE FROM $table WHERE id = ?");
                        $stmt->execute([$_POST['category_id']]);
                    }
                    break;
            }
            header('Location: index.php?page=finances&success=1');
            exit();
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

// Get income categories
$stmt = $db->query("SELECT * FROM income_categories ORDER BY name");
$incomeCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get expense categories
$stmt = $db->query("SELECT * FROM expense_categories ORDER BY name");
$expenseCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get bank accounts
$stmt = $db->query("SELECT * FROM bank_accounts WHERE status = 'active' ORDER BY bank_name");
$bankAccounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get cash funds
$stmt = $db->query("SELECT * FROM cash_funds WHERE status = 'active' ORDER BY name");
$cashFunds = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get date range from parameters
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');
$selectedCategory = isset($_GET['category']) ? $_GET['category'] : '';
$selectedType = isset($_GET['type']) ? $_GET['type'] : '';
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';

// Base query
$query = "SELECT 
    ft.*,
    CASE 
        WHEN ft.type = 'income' THEN ic.name 
        WHEN ft.type = 'expense' THEN ec.name 
        ELSE NULL 
    END as category_name,
    CASE 
        WHEN ft.account_type = 'bank' THEN ba.bank_name
        WHEN ft.account_type = 'cash' THEN cf.name
    END as account_name,
    CASE 
        WHEN ft.transfer_to_type = 'bank' THEN ba2.bank_name
        WHEN ft.transfer_to_type = 'cash' THEN cf2.name
    END as transfer_to_name
FROM financial_transactions ft
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 bank_accounts ba ON ft.account_type = 'bank' AND ft.account_id = ba.id
LEFT JOIN cash_funds cf ON ft.account_type = 'cash' AND ft.account_id = cf.id
LEFT JOIN bank_accounts ba2 ON ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba2.id
LEFT JOIN cash_funds cf2 ON ft.transfer_to_type = 'cash' AND ft.transfer_to_id = cf2.id
WHERE ft.transaction_date BETWEEN :start_date AND :end_date";

// Add filters
$params = [
    ':start_date' => $startDate,
    ':end_date' => $endDate
];

if (!empty($selectedCategory)) {
    $query .= " AND (
        (ft.type = 'income' AND ft.category_id = :category_id) OR 
        (ft.type = 'expense' AND ft.category_id = :category_id)
    )";
    $params[':category_id'] = $selectedCategory;
}

if (!empty($selectedType)) {
    $query .= " AND ft.type = :type";
    $params[':type'] = $selectedType;
}

if (!empty($searchTerm)) {
    $query .= " AND (
        ft.description LIKE :search OR
        ic.name LIKE :search OR
        ec.name LIKE :search OR
        ba.bank_name LIKE :search OR
        cf.name LIKE :search OR
        ba2.bank_name LIKE :search OR
        cf2.name LIKE :search
    )";
    $params[':search'] = '%' . $searchTerm . '%';
}

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

$stmt = $db->prepare($query);
$stmt->execute($params);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals for filtered results
$totals = [
    'income' => 0,
    'expense' => 0,
    'transfer' => 0
];

foreach ($transactions as $transaction) {
    if ($transaction['type'] === 'income') {
        $totals['income'] += $transaction['amount'];
    } elseif ($transaction['type'] === 'expense') {
        $totals['expense'] += $transaction['amount'];
    } elseif ($transaction['type'] === 'transfer') {
        $totals['transfer'] += $transaction['amount'];
    }
}
?>

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

    <!-- Financial Summary -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h5 class="card-title">إجمالي المداخيل</h5>
                    <h3 class="card-text"><?php echo number_format($totals['income'], 2); ?> درهم</h3>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-danger text-white">
                <div class="card-body">
                    <h5 class="card-title">إجمالي المصاريف</h5>
                    <h3 class="card-text"><?php echo number_format($totals['expense'], 2); ?> درهم</h3>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <h5 class="card-title">إجمالي التحويلات</h5>
                    <h3 class="card-text"><?php echo number_format($totals['transfer'], 2); ?> درهم</h3>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card <?php echo $totals['income'] - $totals['expense'] >= 0 ? 'bg-primary' : 'bg-warning'; ?> text-white">
                <div class="card-body">
                    <h5 class="card-title">الرصيد الحالي</h5>
                    <h3 class="card-text"><?php echo number_format($totals['income'] - $totals['expense'], 2); ?> درهم</h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="row mb-4 d-print-none">
        <div class="col-md-12 text-end">
            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addIncomeModal">
                <i class="bi bi-plus-circle"></i> إضافة مدخول
            </button>
            <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#addExpenseModal">
                <i class="bi bi-dash-circle"></i> إضافة مصروف
            </button>
            <button class="btn btn-info text-white" data-bs-toggle="modal" data-bs-target="#transferModal">
                <i class="bi bi-arrow-left-right"></i> تحويل الأموال
            </button>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                <i class="bi bi-folder-plus"></i> إضافة تصنيف
            </button>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="table-container">
        <div class="d-flex justify-content-between align-items-center mb-3 d-print-none">
            <h4>المعاملات المالية</h4>
            <button onclick="window.print()" class="btn btn-secondary btn-sm">
                <i class="fas fa-print"></i> طباعة
            </button>
        </div>

        <!-- Search and Filter Form -->
        <form method="get" class="row g-3 align-items-end mb-4 d-print-none">
            <input type="hidden" name="page" value="finances">
            
            <div class="col-md-2">
                <label class="form-label">من تاريخ</label>
                <input type="date" class="form-control" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>">
            </div>
            
            <div class="col-md-2">
                <label class="form-label">إلى تاريخ</label>
                <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">
            </div>
            
            <div class="col-md-2">
                <label class="form-label">نوع المعاملة</label>
                <select class="form-select" name="type">
                    <option value="">الكل</option>
                    <option value="income" <?php echo $selectedType === 'income' ? 'selected' : ''; ?>>مدخول</option>
                    <option value="expense" <?php echo $selectedType === 'expense' ? 'selected' : ''; ?>>مصروف</option>
                    <option value="transfer" <?php echo $selectedType === 'transfer' ? 'selected' : ''; ?>>تحويل</option>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">التصنيف</label>
                <select class="form-select" name="category">
                    <option value="">الكل</option>
                    <optgroup label="تصنيفات المدخولات">
                        <?php foreach ($incomeCategories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" <?php echo $selectedCategory == $category['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </optgroup>
                    <optgroup label="تصنيفات المصروفات">
                        <?php foreach ($expenseCategories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" <?php echo $selectedCategory == $category['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </optgroup>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">بحث</label>
                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($searchTerm); ?>" placeholder="بحث...">
            </div>
            
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">تطبيق</button>
            </div>
        </form>

        <!-- Totals Summary -->
        <div class="row mb-4 d-print-none">
            <div class="col-md-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المدخولات</h5>
                        <p class="card-text"><?php echo number_format($totals['income'], 2); ?> درهم</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المصاريف</h5>
                        <p class="card-text"><?php echo number_format($totals['expense'], 2); ?> درهم</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي التحويلات</h5>
                        <p class="card-text"><?php echo number_format($totals['transfer'], 2); ?> درهم</p>
                    </div>
                </div>
            </div>
        </div>

        <table class="table table-striped datatable">
            <thead>
                <tr>
                    <th>التاريخ</th>
                    <th>النوع</th>
                    <th>التصنيف</th>
                    <th>المبلغ</th>
                    <th>الوصف</th>
                    <th>الحساب/الصندوق</th>
                    <th class="d-print-none" >التحويل إلى</th>
                    <th class="d-print-none">المسجل</th>
                    <th class="d-print-none">العمليات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactions 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':
                                echo '<span class="badge bg-info">تحويل</span>';
                                break;
                        }
                        ?>
                    </td>
                    <td><?php echo htmlspecialchars($transaction['category_name'] ?? ''); ?></td>
                    <td><?php echo number_format($transaction['amount'], 2); ?> درهم</td>
                    <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                    <td><?php echo htmlspecialchars($transaction['account_name'] ?? ''); ?></td>
                    <td class="d-print-none"><?php echo htmlspecialchars($transaction['transfer_to_name'] ?? ''); ?></td>
                    <td class="d-print-none"><?php echo htmlspecialchars($transaction['created_by_user'] ?? ''); ?></td>
                    <td class="d-print-none">
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteTransaction(<?php echo $transaction['id']; ?>)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Categories Management -->
    <div class="row mt-4 d-print-none">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">تصنيفات المداخيل</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>الاسم</th>
                                    <th>الوصف</th>
                                    <th>العمليات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($incomeCategories as $category): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($category['name']); ?></td>
                                    <td><?php echo htmlspecialchars($category['description']); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_category">
                                            <input type="hidden" name="category_type" value="income">
                                            <input type="hidden" name="category_id" value="<?php echo $category['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>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">تصنيفات المصاريف</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>الاسم</th>
                                    <th>الوصف</th>
                                    <th>العمليات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($expenseCategories as $category): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($category['name']); ?></td>
                                    <td><?php echo htmlspecialchars($category['description']); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_category">
                                            <input type="hidden" name="category_type" value="expense">
                                            <input type="hidden" name="category_id" value="<?php echo $category['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>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Income Modal -->
    <div class="modal fade" id="addIncomeModal" 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="income">
                        <div class="mb-3">
                            <label class="form-label">التصنيف</label>
                            <select class="form-control" name="category_id" required>
                                <?php foreach ($incomeCategories as $category): ?>
                                <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">الحساب</label>
                            <select class="form-control" name="account_type" required>
                                <option value="bank">حساب بنكي</option>
                                <option value="cash">صندوق نقدي</option>
                            </select>
                        </div>
                        <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']); ?></option>
                                <?php endforeach; ?>
                                <?php foreach ($cashFunds as $fund): ?>
                                <option value="<?php echo $fund['id']; ?>"><?php echo htmlspecialchars($fund['name']); ?></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="date" class="form-control" name="transaction_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">طريقة الأداء</label>
                            <select class="form-control" name="payment_method" required>
                                <option value="cash">نقدا</option>
                                <option value="bank">تحويل بنكي</option>
                                <option value="check">شيك</option>
                            </select>
                        </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 Expense Modal -->
    <div class="modal fade" id="addExpenseModal" 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="expense">
                        <div class="mb-3">
                            <label class="form-label">التصنيف</label>
                            <select class="form-control" name="category_id" required>
                                <?php foreach ($expenseCategories as $category): ?>
                                <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">الحساب</label>
                            <select class="form-control" name="account_type" required>
                                <option value="bank">حساب بنكي</option>
                                <option value="cash">صندوق نقدي</option>
                            </select>
                        </div>
                        <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']); ?></option>
                                <?php endforeach; ?>
                                <?php foreach ($cashFunds as $fund): ?>
                                <option value="<?php echo $fund['id']; ?>"><?php echo htmlspecialchars($fund['name']); ?></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="date" class="form-control" name="transaction_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">طريقة الأداء</label>
                            <select class="form-control" name="payment_method" required>
                                <option value="cash">نقدا</option>
                                <option value="bank">تحويل بنكي</option>
                                <option value="check">شيك</option>
                            </select>
                        </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>

    <!-- Add Category Modal -->
    <div class="modal fade" id="addCategoryModal" 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_category">
                        <div class="mb-3">
                            <label class="form-label">نوع التصنيف</label>
                            <select class="form-control" name="category_type" required>
                                <option value="income">مداخيل</option>
                                <option value="expense">مصاريف</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">اسم التصنيف</label>
                            <input type="text" class="form-control" name="name" 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>

    <!-- Transfer Modal -->
    <div class="modal fade" id="transferModal" 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="transfer_funds">
                        
                        <!-- Source Account -->
                        <div class="mb-3">
                            <label class="form-label">من حساب/صندوق</label>
                            <div class="row">
                                <div class="col-md-4">
                                    <select class="form-select" name="source_type" required>
                                        <option value="bank">حساب بنكي</option>
                                        <option value="cash">صندوق مالي</option>
                                    </select>
                                </div>
                                <div class="col-md-8">
                                    <select class="form-select" name="source_id" required>
                                        <optgroup label="الحسابات البنكية">
                                            <?php foreach ($bankAccounts as $account): ?>
                                            <option value="<?php echo $account['id']; ?>" data-type="bank">
                                                <?php echo htmlspecialchars($account['bank_name']); ?> 
                                                (<?php echo number_format($account['balance'], 2); ?> درهم)
                                            </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                        <optgroup label="الصناديق المالية">
                                            <?php foreach ($cashFunds as $fund): ?>
                                            <option value="<?php echo $fund['id']; ?>" data-type="cash">
                                                <?php echo htmlspecialchars($fund['name']); ?>
                                                (<?php echo number_format($fund['balance'], 2); ?> درهم)
                                            </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Destination Account -->
                        <div class="mb-3">
                            <label class="form-label">إلى حساب/صندوق</label>
                            <div class="row">
                                <div class="col-md-4">
                                    <select class="form-select" name="destination_type" required>
                                        <option value="bank">حساب بنكي</option>
                                        <option value="cash">صندوق مالي</option>
                                    </select>
                                </div>
                                <div class="col-md-8">
                                    <select class="form-select" name="destination_id" required>
                                        <optgroup label="الحسابات البنكية">
                                            <?php foreach ($bankAccounts as $account): ?>
                                            <option value="<?php echo $account['id']; ?>" data-type="bank">
                                                <?php echo htmlspecialchars($account['bank_name']); ?>
                                                (<?php echo number_format($account['balance'], 2); ?> درهم)
                                            </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                        <optgroup label="الصناديق المالية">
                                            <?php foreach ($cashFunds as $fund): ?>
                                            <option value="<?php echo $fund['id']; ?>" data-type="cash">
                                                <?php echo htmlspecialchars($fund['name']); ?>
                                                (<?php echo number_format($fund['balance'], 2); ?> درهم)
                                            </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Amount -->
                        <div class="mb-3">
                            <label class="form-label">المبلغ</label>
                            <input type="number" step="0.01" class="form-control" name="amount" required>
                        </div>

                        <!-- Date -->
                        <div class="mb-3">
                            <label class="form-label">التاريخ</label>
                            <input type="date" class="form-control" name="transaction_date" required 
                                value="<?php echo date('Y-m-d'); ?>">
                        </div>

                        <!-- Description -->
                        <div class="mb-3">
                            <label class="form-label">الوصف</label>
                            <textarea class="form-control" name="description" rows="2"></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>

    <!-- Print Modal -->
    <div class="modal fade" id="printModal" 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" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="printForm" method="GET" action="print_financial_transactions.php" target="_blank">
                        <div class="mb-3">
                            <label class="form-label">من تاريخ</label>
                            <input type="date" class="form-control" name="start_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">إلى تاريخ</label>
                            <input type="date" class="form-control" name="end_date" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" form="printForm" class="btn btn-primary">طباعة</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Print Styles -->
    <style media="print">
        @page {
            size: A4;
            margin: 1.5cm;
        }
        
        .no-print {
            display: none !important;
        }
        
        .print-only {
            display: block !important;
        }
        
        body {
            font-size: 12pt;
        }
        
        .table {
            width: 100%;
            margin-bottom: 1rem;
            border-collapse: collapse;
        }
        
        .table th,
        .table td {
            padding: 0.5rem;
            border: 1px solid #dee2e6;
        }
        
        .table thead th {
            background-color: #f8f9fa !important;
            border-bottom: 2px solid #dee2e6;
        }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Set default dates
        const today = new Date();
        const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
        
        document.querySelector('input[name="start_date"]').value = firstDayOfMonth.toISOString().split('T')[0];
        document.querySelector('input[name="end_date"]').value = today.toISOString().split('T')[0];
    });
    </script>

    <script>
    $(document).ready(function() {
        // Set today's date as default for transaction date inputs
        const today = new Date().toISOString().split('T')[0];
        $('input[type="date"]').val(today);
    });
    </script>

    <script>
    // Store accounts and funds data
    const bankAccounts = <?php echo json_encode($bankAccounts); ?>;
    const cashFunds = <?php echo json_encode($cashFunds); ?>;

    // Function to update account options based on selected type
    function updateAccountOptions(modalId) {
        const modal = document.getElementById(modalId);
        const accountType = modal.querySelector('select[name="account_type"]');
        const accountSelect = modal.querySelector('select[name="account_id"]');
        
        accountSelect.innerHTML = ''; // Clear existing options
        
        const accounts = accountType.value === 'bank' ? bankAccounts : cashFunds;
        accounts.forEach(account => {
            const option = document.createElement('option');
            option.value = account.id;
            option.textContent = accountType.value === 'bank' ? account.bank_name : account.name;
            accountSelect.appendChild(option);
        });
    }

    // Add event listeners for both modals
    document.addEventListener('DOMContentLoaded', function() {
        ['addIncomeModal', 'addExpenseModal'].forEach(modalId => {
            const modal = document.getElementById(modalId);
            const accountType = modal.querySelector('select[name="account_type"]');
            
            // Initialize account options
            updateAccountOptions(modalId);
            
            // Update options when account type changes
            accountType.addEventListener('change', () => updateAccountOptions(modalId));
        });
    });
    </script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Handle source type change
        document.querySelector('select[name="source_type"]').addEventListener('change', function() {
            const sourceSelect = document.querySelector('select[name="source_id"]');
            const selectedType = this.value;
            
            Array.from(sourceSelect.options).forEach(option => {
                const optgroup = option.closest('optgroup');
                if (optgroup) {
                    option.style.display = option.dataset.type === selectedType ? '' : 'none';
                    if (option.style.display === 'none') {
                        option.selected = false;
                    }
                }
            });
            
            // Select first visible option
            const firstVisibleOption = Array.from(sourceSelect.options).find(option => 
                option.style.display !== 'none'
            );
            if (firstVisibleOption) {
                firstVisibleOption.selected = true;
            }
        });

        // Handle destination type change
        document.querySelector('select[name="destination_type"]').addEventListener('change', function() {
            const destSelect = document.querySelector('select[name="destination_id"]');
            const selectedType = this.value;
            
            Array.from(destSelect.options).forEach(option => {
                const optgroup = option.closest('optgroup');
                if (optgroup) {
                    option.style.display = option.dataset.type === selectedType ? '' : 'none';
                    if (option.style.display === 'none') {
                        option.selected = false;
                    }
                }
            });
            
            // Select first visible option
            const firstVisibleOption = Array.from(destSelect.options).find(option => 
                option.style.display !== 'none'
            );
            if (firstVisibleOption) {
                firstVisibleOption.selected = true;
            }
        });

        // Trigger initial filtering
        document.querySelector('select[name="source_type"]').dispatchEvent(new Event('change'));
        document.querySelector('select[name="destination_type"]').dispatchEvent(new Event('change'));
    });
    </script>

    <script>
    // Function to handle transaction deletion
    window.deleteTransaction = function(transactionId) {
        if (confirm('هل أنت متأكد من حذف هذه المعاملة المالية؟')) {
            fetch('index.php?page=finances', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=delete_transaction&transaction_id=' + transactionId
            })
            .then(response => response.text())
            .then(data => {
                // Refresh the page to show updated data
                window.location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('حدث خطأ أثناء حذف المعاملة');
            });
        }
    }
    </script>

    <style>
        @media print {
            .d-print-none {
                display: none !important;
            }
            
            .container-fluid {
                width: 100%;
                margin: 0;
                padding: 0;
            }
            
            .table {
                width: 100%;
                margin-bottom: 1rem;
                border-collapse: collapse;
            }
            
            .table th,
            .table td {
                padding: 0.75rem;
                border: 1px solid #dee2e6;
            }
            
            .badge {
                padding: 0.25em 0.4em;
                border: 1px solid #000;
            }
            
            .bg-success {
                background-color: #28a745 !important;
                color: #fff !important;
            }
            
            .bg-danger {
                background-color: #dc3545 !important;
                color: #fff !important;
            }
            
            .bg-info {
                background-color: #17a2b8 !important;
                color: #fff !important;
            }
            
            /* Add summary totals at the bottom of the printed page */
            .table-container::after {
                content: '';
                display: block;
                margin-top: 20px;
                border-top: 2px solid #000;
                padding-top: 10px;
            }
            
            /* Ensure the table fits well on the printed page */
            @page {
                size: landscape;
                margin: 2cm;
            }
        }
    </style>
