<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

try {
    $db = getDB();

    // Get cash fund and bank accounts for the forms
    $cash_fund_stmt = $db->prepare("SELECT id, current_balance FROM cash_fund LIMIT 1");
    $cash_fund_result = $cash_fund_stmt->execute();
    $cash_fund = $cash_fund_result->fetchArray(SQLITE3_ASSOC);

    $bank_accounts_stmt = $db->prepare("SELECT id, bank_name, account_number, current_balance FROM bank_account ORDER BY bank_name");
    $bank_accounts_result = $bank_accounts_stmt->execute();
    $bank_accounts = [];
    while ($account = $bank_accounts_result->fetchArray(SQLITE3_ASSOC)) {
        $bank_accounts[] = $account;
    }

    // Process form submissions
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['action'])) {
            $response = ['success' => false, 'message' => ''];
            
            switch ($_POST['action']) {
                case 'add_invoice_payment':
                    $meter_number = $_POST['meter_number'];
                    $amount = floatval($_POST['amount']);
                    $payment_date = $_POST['payment_date'];
                    
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        // Find the unpaid invoice for this meter number
                        $stmt = $db->prepare("
                            SELECT 
                                i.id, 
                                i.total_amount,
                                i.fixed_fees,
                                i.collective_entitlement_amount,
                                i.consumption_amount,
                                i.penalties,
                                s.full_name,
                                c.previous_reading,
                                c.current_reading,
                                (c.current_reading - c.previous_reading) as consumption,
                                s.family_members
                            FROM invoices i 
                            JOIN subscribers s ON i.subscriber_id = s.id 
                            JOIN consumption c ON i.consumption_id = c.id
                            WHERE s.meter_number = :meter_number 
                            AND (i.status = 'unpaid' OR i.status = 'partially_paid')
                            ORDER BY c.reading_date ASC 
                            LIMIT 1
                        ");
                        $stmt->bindValue(':meter_number', $meter_number, SQLITE3_TEXT);
                        $result = $stmt->execute();
                        $invoice = $result->fetchArray(SQLITE3_ASSOC);
                        
                        if ($invoice) {
                            // Get invoice details
                            $stmt = $db->prepare('
                                SELECT 
                                    i.id,
                                    i.total_amount,
                                    i.status,
                                    s.full_name,
                                    s.meter_number,
                                    c.previous_reading,
                                    c.current_reading,
                                    (c.current_reading - c.previous_reading) as consumption,
                                    i.fixed_fees,
                                    i.collective_entitlement_amount,
                                    i.consumption_amount,
                                    i.penalties
                                FROM invoices i
                                JOIN subscribers s ON i.subscriber_id = s.id
                                JOIN consumption c ON i.consumption_id = c.id
                                WHERE i.id = :id AND i.status != "paid"'
                            );
                            $stmt->bindValue(':id', $invoice['id'], SQLITE3_INTEGER);
                            $result = $stmt->execute();
                            $invoice_details = $result->fetchArray(SQLITE3_ASSOC);

                            if ($invoice_details) {
                                // Update invoice status and payment date
                                $stmt = $db->prepare('
                                    UPDATE invoices 
                                    SET 
                                        status = :status,
                                        payment_date = :payment_date
                                    WHERE id = :id'
                                );
                                $status = ($amount >= $invoice_details['total_amount']) ? 'paid' : 'partially_paid';
                                $stmt->bindValue(':status', $status, SQLITE3_TEXT);
                                $stmt->bindValue(':payment_date', $payment_date, SQLITE3_TEXT);
                                $stmt->bindValue(':id', $invoice['id'], SQLITE3_INTEGER);
                                $stmt->execute();

                                // Insert payment record
                                $stmt = $db->prepare('
                                    INSERT INTO payments (
                                        invoice_id,
                                        amount,
                                        payment_date,
                                        payment_method,
                                        notes
                                    ) VALUES (
                                        :invoice_id,
                                        :amount,
                                        :payment_date,
                                        :payment_method,
                                        :notes
                                    )'
                                );
                                $stmt->bindValue(':invoice_id', $invoice['id'], SQLITE3_INTEGER);
                                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                                $stmt->bindValue(':payment_date', $payment_date, SQLITE3_TEXT);
                                $stmt->bindValue(':payment_method', 'cash', SQLITE3_TEXT);
                                $stmt->bindValue(':notes', '', SQLITE3_TEXT);
                                $stmt->execute();

                                // Update cash fund balance
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + ?, updated_at = CURRENT_TIMESTAMP");
                                $stmt->execute([$amount]);

                                // Record transaction in financial_transactions
                                $stmt = $db->prepare("INSERT INTO financial_transactions (
                                    transaction_type, 
                                    amount, 
                                    source_type,
                                    source_id,
                                    description,
                                    reference_type,
                                    reference_id
                                ) VALUES (
                                    'DEPOSIT',
                                    ?,
                                    'CASH_FUND',
                                    (SELECT id FROM cash_fund LIMIT 1),
                                    'تسديد الفاتورة رقم ' || ?,
                                    'INVOICE',
                                    ?
                                )");
                                $stmt->execute([$amount, $invoice['id'], $invoice['id']]);

                                $db->exec('COMMIT');
                                
                                // Prepare detailed response
                                $response['success'] = true;
                                $response['message'] = "تم تسجيل الدفع بنجاح للمشترك: " . $invoice['full_name'];
                                $response['details'] = [
                                    'full_name' => $invoice['full_name'],
                                    'consumption' => $invoice['consumption'],
                                    'fixed_fees' => $invoice['fixed_fees'],
                                    'collective_entitlement' => $invoice['collective_entitlement_amount'],
                                    'consumption_amount' => $invoice['consumption_amount'],
                                    'penalties' => $invoice['penalties'],
                                    'total_amount' => $invoice['total_amount'],
                                    'amount_paid' => $amount,
                                    'remaining' => $invoice['total_amount'] - $amount,
                                    'status' => $status
                                ];
                            } else {
                                throw new Exception("لم يتم العثور على فاتورة غير مدفوعة لهذا العداد");
                            }
                        } else {
                            throw new Exception("لم يتم العثور على فاتورة غير مدفوعة لهذا العداد");
                        }
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        throw $e;
                    }
                    break;

                case 'add_new_subscriber':
                    $meter_number = $_POST['meter_number'];
                    $amount = floatval($_POST['amount']);
                    $payment_date = $_POST['payment_date'];
                    
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        // Get subscriber details
                        $stmt = $db->prepare("SELECT id, full_name FROM subscribers WHERE meter_number = ?");
                        $stmt->execute([$meter_number]);
                        $subscriber = $stmt->fetchArray(SQLITE3_ASSOC);
                        
                        if ($subscriber) {
                            // Insert payment record
                            $stmt = $db->prepare("INSERT INTO subscriber_payments (
                                subscriber_id,
                                amount,
                                payment_date,
                                payment_type,
                                notes
                            ) VALUES (?, ?, ?, 'new_subscription', '')");
                            $stmt->execute([$subscriber['id'], $amount, $payment_date]);
                            
                            // Update cash fund balance
                            $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + ?, updated_at = CURRENT_TIMESTAMP");
                            $stmt->execute([$amount]);

                            // Record transaction in financial_transactions
                            $stmt = $db->prepare("INSERT INTO financial_transactions (
                                transaction_type, 
                                amount, 
                                source_type,
                                source_id,
                                description
                            ) VALUES (
                                'DEPOSIT',
                                ?,
                                'CASH_FUND',
                                (SELECT id FROM cash_fund LIMIT 1),
                                'رسوم اشتراك جديد - العداد رقم ' || ?
                            )");
                            $stmt->execute([$amount, $meter_number]);

                            $db->exec('COMMIT');
                            $response['success'] = true;
                            $response['message'] = "تم تسجيل الدفع بنجاح للمشترك " . $subscriber['full_name'];
                        } else {
                            throw new Exception("لم يتم العثور على مشترك بهذا الرقم");
                        }
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        throw $e;
                    }
                    break;

                case 'add_expense':
                    $amount = floatval($_POST['amount']);
                    $reason = $_POST['reason'];
                    $expense_date = $_POST['expense_date'];
                    $source_type = $_POST['source_type'];
                    $source_id = intval($_POST['source_id']);
                    
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        // Check if source has sufficient balance
                        if ($source_type === 'CASH_FUND') {
                            $stmt = $db->prepare("SELECT id, current_balance FROM cash_fund WHERE current_balance >= :amount LIMIT 1");
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $result = $stmt->execute();
                            $cash_fund = $result->fetchArray(SQLITE3_ASSOC);
                            
                            if (!$cash_fund) {
                                throw new Exception("رصيد الصندوق غير كافي");
                            }
                            
                            $source_id = $cash_fund['id'];
                            
                            // Update cash fund balance
                            $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance - :amount WHERE id = :id");
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                            $stmt->execute();
                        } else if ($source_type === 'BANK_ACCOUNT') {
                            $stmt = $db->prepare("SELECT current_balance FROM bank_account WHERE id = :id AND current_balance >= :amount");
                            $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $result = $stmt->execute();
                            if (!$result->fetchArray()) {
                                throw new Exception("رصيد الحساب البنكي غير كافي");
                            }
                            
                            // Update bank account balance
                            $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance - :amount WHERE id = :id");
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                            $stmt->execute();
                        }

                        // Record transaction
                        $stmt = $db->prepare("
                            INSERT INTO financial_transactions (
                                transaction_type,
                                amount,
                                source_type,
                                source_id,
                                description,
                                created_at
                            ) VALUES (
                                'WITHDRAWAL',
                                :amount,
                                :source_type,
                                :source_id,
                                :description,
                                :created_at
                            )
                        ");
                        
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':source_type', $source_type, SQLITE3_TEXT);
                        $stmt->bindValue(':source_id', $source_id, SQLITE3_INTEGER);
                        $stmt->bindValue(':description', "مصروف: " . $reason, SQLITE3_TEXT);
                        $stmt->bindValue(':created_at', $expense_date, SQLITE3_TEXT);
                        $stmt->execute();

                        $db->exec('COMMIT');
                        $response['success'] = true;
                        $response['message'] = "تم تسجيل المصروف بنجاح";
                        
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        $response['success'] = false;
                        $response['message'] = $e->getMessage();
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;
                    }
                    break;

                case 'add_contribution':
                    $amount = floatval($_POST['amount']);
                    $reason = $_POST['reason'];
                    $contribution_date = $_POST['contribution_date'];
                    $source_type = $_POST['source_type'];
                    $source_id = intval($_POST['source_id']);
                    
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        // Get cash fund ID if cash fund is selected
                        if ($source_type === 'CASH_FUND') {
                            $stmt = $db->prepare("SELECT id FROM cash_fund LIMIT 1");
                            $result = $stmt->execute();
                            $cash_fund = $result->fetchArray(SQLITE3_ASSOC);
                            if (!$cash_fund) {
                                throw new Exception("لم يتم العثور على الصندوق");
                            }
                            $source_id = $cash_fund['id'];
                        }
                        
                        // Update source balance
                        if ($source_type === 'CASH_FUND') {
                            $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + :amount WHERE id = :id");
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                            $stmt->execute();
                        } else if ($source_type === 'BANK_ACCOUNT') {
                            $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance + :amount WHERE id = :id");
                            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                            $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                            $stmt->execute();
                        }

                        // Record transaction
                        $stmt = $db->prepare("
                            INSERT INTO financial_transactions (
                                transaction_type,
                                amount,
                                source_type,
                                source_id,
                                description,
                                created_at
                            ) VALUES (
                                'DEPOSIT',
                                :amount,
                                :source_type,
                                :source_id,
                                :description,
                                :created_at
                            )
                        ");
                        
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':source_type', $source_type, SQLITE3_TEXT);
                        $stmt->bindValue(':source_id', $source_id, SQLITE3_INTEGER);
                        $stmt->bindValue(':description', "مساهمة: " . $reason, SQLITE3_TEXT);
                        $stmt->bindValue(':created_at', $contribution_date, SQLITE3_TEXT);
                        $stmt->execute();

                        $db->exec('COMMIT');
                        $response['success'] = true;
                        $response['message'] = "تم تسجيل المساهمة بنجاح";
                        
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        $response['success'] = false;
                        $response['message'] = $e->getMessage();
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;
                    }
                    break;

                case 'add_transaction':
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        $amount = floatval($_POST['amount']);
                        $transaction_type = $_POST['transaction_type'];
                        $source_type = $_POST['source_type'];
                        $source_id = intval($_POST['source_id']);
                        $description = $_POST['description'];
                        $transaction_date = $_POST['transaction_date'];
                        
                        // Validate amount
                        if ($amount <= 0) {
                            throw new Exception("المبلغ يجب أن يكون أكبر من 0");
                        }
                        
                        // Check source balance for withdrawals
                        if ($transaction_type === 'WITHDRAWAL') {
                            if ($source_type === 'CASH_FUND') {
                                $stmt = $db->prepare("SELECT current_balance FROM cash_fund WHERE id = :id");
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $result = $stmt->execute();
                                $fund = $result->fetchArray(SQLITE3_ASSOC);
                                
                                if (!$fund || $fund['current_balance'] < $amount) {
                                    throw new Exception("رصيد الصندوق غير كافي");
                                }
                                
                                // Update cash fund balance
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance - :amount WHERE id = :id");
                                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $stmt->execute();
                                
                            } else if ($source_type === 'BANK_ACCOUNT') {
                                $stmt = $db->prepare("SELECT current_balance FROM bank_account WHERE id = :id");
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $result = $stmt->execute();
                                $account = $result->fetchArray(SQLITE3_ASSOC);
                                
                                if (!$account || $account['current_balance'] < $amount) {
                                    throw new Exception("رصيد الحساب البنكي غير كافي");
                                }
                                
                                // Update bank account balance
                                $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance - :amount WHERE id = :id");
                                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $stmt->execute();
                            }
                        } else if ($transaction_type === 'DEPOSIT') {
                            if ($source_type === 'CASH_FUND') {
                                // Update cash fund balance
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + :amount WHERE id = :id");
                                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $stmt->execute();
                                
                            } else if ($source_type === 'BANK_ACCOUNT') {
                                // Update bank account balance
                                $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance + :amount WHERE id = :id");
                                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                                $stmt->bindValue(':id', $source_id, SQLITE3_INTEGER);
                                $stmt->execute();
                            }
                        }
                        
                        // Record the transaction
                        $stmt = $db->prepare("
                            INSERT INTO financial_transactions (
                                transaction_type, 
                                amount, 
                                source_type, 
                                source_id, 
                                description,
                                created_at
                            ) VALUES (
                                :transaction_type,
                                :amount,
                                :source_type,
                                :source_id,
                                :description,
                                :created_at
                            )
                        ");
                        
                        $stmt->bindValue(':transaction_type', $transaction_type, SQLITE3_TEXT);
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':source_type', $source_type, SQLITE3_TEXT);
                        $stmt->bindValue(':source_id', $source_id, SQLITE3_INTEGER);
                        $stmt->bindValue(':description', $description, SQLITE3_TEXT);
                        $stmt->bindValue(':created_at', $transaction_date . ' ' . date('H:i:s'), SQLITE3_TEXT);
                        $stmt->execute();
                        
                        $db->exec('COMMIT');
                        $response['success'] = true;
                        $response['message'] = 'تم تسجيل المعاملة بنجاح';
                        
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        throw $e;
                    }
                    break;

                case 'delete_transaction':
                    $transaction_id = intval($_POST['transaction_id']);
                    
                    try {
                        $db->exec('BEGIN TRANSACTION');
                        
                        // Get transaction details
                        $stmt = $db->prepare("SELECT * FROM financial_transactions WHERE id = :id");
                        $stmt->bindValue(':id', $transaction_id, SQLITE3_INTEGER);
                        $result = $stmt->execute();
                        $transaction = $result->fetchArray(SQLITE3_ASSOC);
                        
                        if (!$transaction) {
                            throw new Exception("لم يتم العثور على المعاملة");
                        }
                        
                        // Reverse the transaction effect on balance
                        if ($transaction['transaction_type'] === 'WITHDRAWAL') {
                            // For withdrawals, add the amount back
                            if ($transaction['source_type'] === 'CASH_FUND') {
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + :amount WHERE id = :id");
                            } else {
                                $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance + :amount WHERE id = :id");
                            }
                        } else {
                            // For deposits, subtract the amount
                            if ($transaction['source_type'] === 'CASH_FUND') {
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance - :amount WHERE id = :id");
                            } else {
                                $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance - :amount WHERE id = :id");
                            }
                        }
                        
                        $stmt->bindValue(':amount', $transaction['amount'], SQLITE3_FLOAT);
                        $stmt->bindValue(':id', $transaction['source_id'], SQLITE3_INTEGER);
                        $stmt->execute();
                        
                        // Delete the transaction
                        $stmt = $db->prepare("DELETE FROM financial_transactions WHERE id = :id");
                        $stmt->bindValue(':id', $transaction_id, SQLITE3_INTEGER);
                        $stmt->execute();
                        
                        $db->exec('COMMIT');
                        $response['success'] = true;
                        $response['message'] = "تم حذف المعاملة بنجاح";
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        $response['success'] = false;
                        $response['message'] = $e->getMessage();
                    }
                    
                    header('Content-Type: application/json');
                    echo json_encode($response);
                    exit;
                    break;
            }
            
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }
    }
} catch (Exception $e) {
    error_log("ERREUR CRITIQUE - financial_entry.php: " . $e->getMessage());
    error_log("Trace: " . $e->getTraceAsString());
    if (isset($response)) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    die("خطأ في معالجة البيانات: " . htmlspecialchars($e->getMessage()));
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل المعاملات المالية</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/dashboard.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'includes/sidebar.php'; ?>

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">تسجيل المعاملات المالية</h1>
                    <a href="financial_report.php" class="btn btn-primary">عرض التقرير المالي</a>
                </div>

                <div class="row mb-4">
                    <!-- Add Invoice Payment -->


                
                    <!-- Add Expense -->
                    <div class="col-md-3">
                        <div class="card">
                            <div class="card-header">تسجيل مصروف</div>
                            <div class="card-body">
                                <form id="expenseForm">
                                    <input type="hidden" name="action" value="add_expense">
                                    
                                    <div class="mb-3">
                                        <label for="expense_source_type" class="form-label">المصدر</label>
                                        <select class="form-select" id="expense_source_type" name="source_type" required>
                                            <option value="">اختر المصدر</option>
                                            <option value="CASH_FUND">الصندوق</option>
                                            <option value="BANK_ACCOUNT">حساب بنكي</option>
                                        </select>
                                    </div>

                                    <div class="mb-3" id="expense_bank_account_div" style="display: none;">
                                        <label for="expense_source_id" class="form-label">الحساب البنكي</label>
                                        <select class="form-select" id="expense_source_id" name="source_id">
                                            <?php foreach ($bank_accounts as $account): ?>
                                                <option value="<?php echo $account['id']; ?>">
                                                    <?php echo $account['bank_name'] . ' - ' . $account['account_number'] . 
                                                          ' (الرصيد: ' . number_format($account['current_balance'], 2) . ' درهم)'; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

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

                                    <div class="mb-3">
                                        <label for="expense_reason" class="form-label">السبب</label>
                                        <input type="text" class="form-control" id="expense_reason" name="reason" required>
                                    </div>

                                    <div class="mb-3">
                                        <label for="expense_date" class="form-label">التاريخ</label>
                                        <input type="date" class="form-control" id="expense_date" name="expense_date" required>
                                    </div>

                                    <button type="submit" class="btn btn-primary">تسجيل</button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Add Contribution -->
                    <div class="col-md-3">
                        <div class="card">
                            <div class="card-header">تسجيل مساهمة</div>
                            <div class="card-body">
                                <form id="contributionForm">
                                    <input type="hidden" name="action" value="add_contribution">
                                    
                                    <div class="mb-3">
                                        <label for="contribution_source_type" class="form-label">المصدر</label>
                                        <select class="form-select" id="contribution_source_type" name="source_type" required>
                                            <option value="">اختر المصدر</option>
                                            <option value="CASH_FUND">الصندوق</option>
                                            <option value="BANK_ACCOUNT">حساب بنكي</option>
                                        </select>
                                    </div>

                                    <div class="mb-3" id="contribution_bank_account_div" style="display: none;">
                                        <label for="contribution_source_id" class="form-label">الحساب البنكي</label>
                                        <select class="form-select" id="contribution_source_id" name="source_id">
                                            <?php foreach ($bank_accounts as $account): ?>
                                                <option value="<?php echo $account['id']; ?>">
                                                    <?php echo $account['bank_name'] . ' - ' . $account['account_number'] . 
                                                          ' (الرصيد: ' . number_format($account['current_balance'], 2) . ' درهم)'; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

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

                                    <div class="mb-3">
                                        <label for="contribution_reason" class="form-label">السبب</label>
                                        <input type="text" class="form-control" id="contribution_reason" name="reason" required>
                                    </div>

                                    <div class="mb-3">
                                        <label for="contribution_date" class="form-label">التاريخ</label>
                                        <input type="date" class="form-control" id="contribution_date" name="contribution_date" required>
                                    </div>

                                    <button type="submit" class="btn btn-primary">تسجيل</button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Add Transaction -->
                   
                </div>

                <!-- Transactions List -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h4>سجل المعاملات</h4>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>التاريخ</th>
                                        <th>نوع المعاملة</th>
                                        <th>المصدر</th>
                                        <th>المبلغ</th>
                                        <th>الوصف</th>
                                        <th>الإجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Get transactions
                                    $stmt = $db->prepare("
                                        SELECT 
                                            ft.*,
                                            CASE 
                                                WHEN ft.source_type = 'CASH_FUND' THEN 'الصندوق'
                                                WHEN ft.source_type = 'BANK_ACCOUNT' THEN (SELECT bank_name || ' - ' || account_number FROM bank_account WHERE id = ft.source_id)
                                            END as source_name
                                        FROM financial_transactions ft
                                        ORDER BY ft.created_at DESC
                                        LIMIT 100
                                    ");
                                    $result = $stmt->execute();
                                    
                                    while ($transaction = $result->fetchArray(SQLITE3_ASSOC)) {
                                        $transaction_type = $transaction['transaction_type'] === 'DEPOSIT' ? 'إيداع' : 'سحب';
                                        $amount_class = $transaction['transaction_type'] === 'DEPOSIT' ? 'text-success' : 'text-danger';
                                        $amount_prefix = $transaction['transaction_type'] === 'DEPOSIT' ? '+' : '-';
                                        ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d H:i', strtotime($transaction['created_at'])); ?></td>
                                            <td><?php echo $transaction_type; ?></td>
                                            <td><?php echo htmlspecialchars($transaction['source_name']); ?></td>
                                            <td class="<?php echo $amount_class; ?>">
                                                <?php echo $amount_prefix . number_format($transaction['amount'], 2); ?> درهم
                                            </td>
                                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                            <td>
                                                <button type="button" 
                                                        class="btn btn-danger btn-sm delete-transaction" 
                                                        data-id="<?php echo $transaction['id']; ?>">
                                                    <i class="bi bi-trash"></i> حذف
                                                </button>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // Set default date to today
            const today = new Date().toISOString().split('T')[0];
            $('input[type="date"]').val(today);

            // Prevent double form submission
            $('form').on('submit', function() {
                $(this).find('button[type="submit"]').prop('disabled', true);
            });

            // Handle source type change for expense form
            $('#expense_source_type').change(function() {
                if ($(this).val() === 'BANK_ACCOUNT') {
                    $('#expense_bank_account_div').show();
                    $('#expense_source_id').prop('required', true);
                } else {
                    $('#expense_bank_account_div').hide();
                    $('#expense_source_id').prop('required', false);
                }
            });

            // Handle source type change for contribution form
            $('#contribution_source_type').change(function() {
                if ($(this).val() === 'BANK_ACCOUNT') {
                    $('#contribution_bank_account_div').show();
                    $('#contribution_source_id').prop('required', true);
                } else {
                    $('#contribution_bank_account_div').hide();
                    $('#contribution_source_id').prop('required', false);
                }
            });

            // Handle expense form submission
            $('#expenseForm').on('submit', function(e) {
                e.preventDefault();
                var form = $(this);
                var submitButton = form.find('button[type="submit"]');
                submitButton.prop('disabled', true);
                
                $.ajax({
                    url: 'financial_entry.php',
                    type: 'POST',
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                        if (response.success) {
                            location.reload();
                        } else {
                            submitButton.prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('حدث خطأ في الاتصال بالخادم');
                        submitButton.prop('disabled', false);
                    }
                });
            });

            // Handle contribution form submission
            $('#contributionForm').on('submit', function(e) {
                e.preventDefault();
                var form = $(this);
                var submitButton = form.find('button[type="submit"]');
                submitButton.prop('disabled', true);
                
                $.ajax({
                    url: 'financial_entry.php',
                    type: 'POST',
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                        if (response.success) {
                            location.reload();
                        } else {
                            submitButton.prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('حدث خطأ في الاتصال بالخادم');
                        submitButton.prop('disabled', false);
                    }
                });
            });

            // Handle transaction deletion
            $('.delete-transaction').on('click', function() {
                if (!confirm('هل أنت متأكد من حذف هذه المعاملة؟')) {
                    return;
                }
                
                var button = $(this);
                button.prop('disabled', true);
                
                $.ajax({
                    url: 'financial_entry.php',
                    type: 'POST',
                    data: {
                        action: 'delete_transaction',
                        transaction_id: button.data('id')
                    },
                    dataType: 'json',
                    success: function(response) {
                        alert(response.message);
                        if (response.success) {
                            location.reload();
                        } else {
                            button.prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('حدث خطأ في الاتصال بالخادم');
                        button.prop('disabled', false);
                    }
                });
            });
        });
    </script>
</body>
</html>
