<?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');

$db = getDB();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            $db->exec('BEGIN TRANSACTION');
            
            switch ($_POST['action']) {
                case 'create':
                    $stmt = $db->prepare("INSERT INTO bank_account (account_number, bank_name, initial_balance, current_balance) VALUES (:account_number, :bank_name, :initial_balance, :current_balance)");
                    $initial_balance = floatval($_POST['initial_balance']);
                    $stmt->bindValue(':account_number', $_POST['account_number'], SQLITE3_TEXT);
                    $stmt->bindValue(':bank_name', $_POST['bank_name'], SQLITE3_TEXT);
                    $stmt->bindValue(':initial_balance', $initial_balance, SQLITE3_FLOAT);
                    $stmt->bindValue(':current_balance', $initial_balance, SQLITE3_FLOAT);
                    $stmt->execute();
                    break;
                
                case 'update':
                    $stmt = $db->prepare("UPDATE bank_account SET account_number = :account_number, bank_name = :bank_name, current_balance = :current_balance, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
                    $stmt->bindValue(':account_number', $_POST['account_number'], SQLITE3_TEXT);
                    $stmt->bindValue(':bank_name', $_POST['bank_name'], SQLITE3_TEXT);
                    $stmt->bindValue(':current_balance', floatval($_POST['current_balance']), SQLITE3_FLOAT);
                    $stmt->bindValue(':id', $_POST['account_id'], SQLITE3_INTEGER);
                    $stmt->execute();
                    break;
                
                case 'delete':
                    try {
                        $account_id = intval($_POST['account_id']);
                        
                        // Start by getting all transactions related to this bank account
                        $stmt = $db->prepare("
                            SELECT * FROM financial_transactions 
                            WHERE (source_type = 'BANK_ACCOUNT' AND source_id = :account_id)
                            OR (destination_type = 'BANK_ACCOUNT' AND destination_id = :account_id)
                        ");
                        $stmt->bindValue(':account_id', $account_id, SQLITE3_INTEGER);
                        $result = $stmt->execute();
                        
                        // Reverse all transactions
                        while ($transaction = $result->fetchArray(SQLITE3_ASSOC)) {
                            if ($transaction['source_type'] === 'CASH_FUND' && $transaction['transaction_type'] === 'DEPOSIT') {
                                // Update cash fund balance
                                $stmt = $db->prepare("UPDATE cash_fund 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();
                            } else if ($transaction['destination_type'] === 'CASH_FUND' && $transaction['transaction_type'] === 'WITHDRAWAL') {
                                // Update cash fund balance
                                $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance - :amount WHERE id = :id");
                                $stmt->bindValue(':amount', $transaction['amount'], SQLITE3_FLOAT);
                                $stmt->bindValue(':id', $transaction['destination_id'], SQLITE3_INTEGER);
                                $stmt->execute();
                            }
                        }
                        
                        // Delete all related transactions
                        $stmt = $db->prepare("
                            DELETE FROM financial_transactions 
                            WHERE (source_type = 'BANK_ACCOUNT' AND source_id = :account_id)
                            OR (destination_type = 'BANK_ACCOUNT' AND destination_id = :account_id)
                        ");
                        $stmt->bindValue(':account_id', $account_id, SQLITE3_INTEGER);
                        $stmt->execute();
                        
                        // Finally delete the bank account
                        $stmt = $db->prepare("DELETE FROM bank_account WHERE id = :id");
                        $stmt->bindValue(':id', $account_id, SQLITE3_INTEGER);
                        $stmt->execute();
                        
                        $db->exec('COMMIT');
                        header('Location: bank_account.php');
                        exit;
                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        $error_message = $e->getMessage();
                    }
                    break;
                
                case 'transfer':
                    $amount = floatval($_POST['amount']);
                    $source_type = $_POST['source_type'];
                    $destination_type = $_POST['source_type'] === 'CASH_FUND' ? 'BANK_ACCOUNT' : 'CASH_FUND';
                    
                    // Update source balance
                    if ($source_type === 'CASH_FUND') {
                        $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance - :amount, updated_at = CURRENT_TIMESTAMP WHERE id = :id AND current_balance >= :check_amount");
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':id', $_POST['source_id'], SQLITE3_INTEGER);
                        $stmt->bindValue(':check_amount', $amount, SQLITE3_FLOAT);
                        $stmt->execute();
                        if ($db->changes() === 0) {
                            throw new Exception("رصيد الصندوق غير كافي");
                        }
                    } else {
                        $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance - :amount, updated_at = CURRENT_TIMESTAMP WHERE id = :id AND current_balance >= :check_amount");
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':id', $_POST['source_id'], SQLITE3_INTEGER);
                        $stmt->bindValue(':check_amount', $amount, SQLITE3_FLOAT);
                        $stmt->execute();
                        if ($db->changes() === 0) {
                            throw new Exception("رصيد الحساب البنكي غير كافي");
                        }
                    }

                    // Update destination balance
                    if ($destination_type === 'CASH_FUND') {
                        $stmt = $db->prepare("UPDATE cash_fund SET current_balance = current_balance + :amount, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':id', $_POST['destination_id'], SQLITE3_INTEGER);
                        $stmt->execute();
                    } else {
                        $stmt = $db->prepare("UPDATE bank_account SET current_balance = current_balance + :amount, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
                        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                        $stmt->bindValue(':id', $_POST['destination_id'], SQLITE3_INTEGER);
                        $stmt->execute();
                    }

                    // Record transaction
                    $stmt = $db->prepare("INSERT INTO financial_transactions (
                        transaction_type, amount, source_type, source_id, 
                        destination_type, destination_id, description
                    ) VALUES ('TRANSFER', :amount, :source_type, :source_id, :destination_type, :destination_id, :description)");
                    $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                    $stmt->bindValue(':source_type', $source_type, SQLITE3_TEXT);
                    $stmt->bindValue(':source_id', $_POST['source_id'], SQLITE3_INTEGER);
                    $stmt->bindValue(':destination_type', $destination_type, SQLITE3_TEXT);
                    $stmt->bindValue(':destination_id', $_POST['destination_id'], SQLITE3_INTEGER);
                    $stmt->bindValue(':description', "تحويل بين الصندوق والحساب البنكي", SQLITE3_TEXT);
                    $stmt->execute();
                    break;

                case 'delete_transaction':
                    $transaction_id = intval($_POST['transaction_id']);
                    $amount = floatval($_POST['amount']);
                    $transaction_type = $_POST['transaction_type'];
                    $source_type = $_POST['source_type'];
                    $source_id = intval($_POST['source_id']);

                    try {
                        // Get the transaction details first
                        $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 transaction only for existing accounts
                        if ($transaction_type === 'WITHDRAWAL') {
                            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') {
                                // Only update bank account if it still exists
                                $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') {
                                // Only update bank account if it still exists
                                $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();
                            }
                        }

                        // Delete 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, 'message' => 'تم حذف المعاملة بنجاح'];
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;

                    } catch (Exception $e) {
                        $db->exec('ROLLBACK');
                        $response = ['success' => false, 'message' => $e->getMessage()];
                        header('Content-Type: application/json');
                        echo json_encode($response);
                        exit;
                    }
                    break;

                default:
                    throw new Exception("Action not supported");
            }
            
            $db->exec('COMMIT');
            header('Location: bank_account.php');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            $error_message = $e->getMessage();
        }
    }
}

// Get bank accounts
$stmt = $db->prepare("SELECT * FROM bank_account ORDER BY id DESC");
$result = $stmt->execute();
$bank_accounts = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $bank_accounts[] = $row;
}

// Get cash fund for transfers
$stmt = $db->prepare("SELECT * FROM cash_fund ORDER BY id DESC LIMIT 1");
$result = $stmt->execute();
$cash_fund = $result->fetchArray(SQLITE3_ASSOC);

// Get recent transactions
$stmt = $db->prepare("
    SELECT 
        ft.*,
        CASE 
            WHEN source_type = 'BANK_ACCOUNT' THEN (SELECT bank_name || ' - ' || account_number FROM bank_account WHERE id = ft.source_id)
            ELSE 'الصندوق'
        END as source_name,
        CASE 
            WHEN destination_type = 'BANK_ACCOUNT' THEN (SELECT bank_name || ' - ' || account_number FROM bank_account WHERE id = ft.destination_id)
            ELSE 'الصندوق'
        END as destination_name
    FROM financial_transactions ft
    WHERE source_type = 'BANK_ACCOUNT' OR destination_type = 'BANK_ACCOUNT'
    ORDER BY created_at DESC
    LIMIT 50
");
$result = $stmt->execute();
$transactions = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $transactions[] = $row;
}

require_once 'includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php require_once 'includes/sidebar.php'; ?>
        
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <h2 class="my-4">إدارة الحسابات البنكية</h2>

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

            <!-- Create Bank Account Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h4>إضافة حساب بنكي</h4>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="create">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>رقم الحساب</label>
                                    <input type="text" name="account_number" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>اسم البنك</label>
                                    <input type="text" name="bank_name" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>الرصيد الأساسي (درهم)</label>
                                    <input type="number" step="0.01" name="initial_balance" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-3">إضافة</button>
                    </form>
                </div>
            </div>

            <!-- Transfer Form -->
            <?php if ($cash_fund && !empty($bank_accounts)): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <h4>إجراء تحويل</h4>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="transfer">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>المصدر</label>
                                    <select name="source_type" class="form-control" required>
                                        <option value="CASH_FUND">الصندوق</option>
                                        <option value="BANK_ACCOUNT">حساب بنكي</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>حساب المصدر</label>
                                    <select name="source_id" class="form-control" required>
                                        <option value="<?= $cash_fund['id'] ?>" data-type="CASH_FUND">
                                            الصندوق (<?= number_format($cash_fund['current_balance'], 2) ?> درهم)
                                        </option>
                                        <?php foreach ($bank_accounts as $account): ?>
                                        <option value="<?= $account['id'] ?>" data-type="BANK_ACCOUNT">
                                            <?= $account['bank_name'] ?> - <?= $account['account_number'] ?> 
                                            (<?= number_format($account['current_balance'], 2) ?> درهم)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>حساب الوجهة</label>
                                    <select name="destination_id" class="form-control" required>
                                        <option value="<?= $cash_fund['id'] ?>" data-type="CASH_FUND">
                                            الصندوق (<?= number_format($cash_fund['current_balance'], 2) ?> درهم)
                                        </option>
                                        <?php foreach ($bank_accounts as $account): ?>
                                        <option value="<?= $account['id'] ?>" data-type="BANK_ACCOUNT">
                                            <?= $account['bank_name'] ?> - <?= $account['account_number'] ?>
                                            (<?= number_format($account['current_balance'], 2) ?> درهم)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>المبلغ (درهم)</label>
                                    <input type="number" step="0.01" name="amount" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-3">إجراء التحويل</button>
                    </form>
                </div>
            </div>
            <?php endif; ?>

            <!-- Bank Accounts List -->
            <div class="card mb-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 foreach ($bank_accounts as $account): ?>
                                <tr>
                                    <td><?= htmlspecialchars($account['bank_name']) ?></td>
                                    <td><?= htmlspecialchars($account['account_number']) ?></td>
                                    <td><?= number_format($account['initial_balance'], 2) ?></td>
                                    <td><?= number_format($account['current_balance'], 2) ?></td>
                                    <td><?= $account['updated_at'] ?></td>
                                    <td>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="account_id" value="<?= $account['id'] ?>">
                                            <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('هل أنت متأكد من حذف هذا الحساب؟')">
                                                حذف
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Transactions History -->
            <div class="card">
                <div class="card-header">
                    <h4>سجل المعاملات</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>التاريخ</th>
                                    <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,
                                        CASE 
                                            WHEN ft.destination_type = 'CASH_FUND' THEN 'صندوق النقد'
                                            WHEN ft.destination_type = 'BANK_ACCOUNT' THEN (SELECT bank_name || ' - ' || account_number FROM bank_account WHERE id = ft.destination_id)
                                        END as destination_name
                                    FROM financial_transactions ft
                                    WHERE ft.source_type = 'BANK_ACCOUNT' OR ft.destination_type = 'BANK_ACCOUNT'
                                    ORDER BY ft.created_at DESC
                                    LIMIT 100
                                ");
                                $result = $stmt->execute();
                                
                                while ($transaction = $result->fetchArray(SQLITE3_ASSOC)) {
                                    $transaction_type_text = $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_text; ?></td>
                                        <td><?php echo htmlspecialchars($transaction['source_name']); ?></td>
                                        <td><?php echo htmlspecialchars($transaction['destination_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']; ?>"
                                                    data-amount="<?php echo $transaction['amount']; ?>"
                                                    data-type="<?php echo $transaction['transaction_type']; ?>"
                                                    data-source-type="<?php echo $transaction['source_type']; ?>"
                                                    data-source-id="<?php echo $transaction['source_id']; ?>">
                                                <i class="bi bi-trash"></i> حذف
                                            </button>
                                        </td>
                                    </tr>
                                    <?php
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle source type change
    const sourceTypeSelect = document.querySelector('select[name="source_type"]');
    const sourceIdSelect = document.querySelector('select[name="source_id"]');
    const destinationIdSelect = document.querySelector('select[name="destination_id"]');

    if (sourceTypeSelect && sourceIdSelect && destinationIdSelect) {
        sourceTypeSelect.addEventListener('change', function() {
            const selectedType = this.value;
            
            // Show only relevant source options
            Array.from(sourceIdSelect.options).forEach(option => {
                if (option.dataset.type === selectedType) {
                    option.style.display = '';
                } else {
                    option.style.display = 'none';
                }
            });
            sourceIdSelect.value = '';

            // Show only relevant destination options
            Array.from(destinationIdSelect.options).forEach(option => {
                if (option.dataset.type !== selectedType) {
                    option.style.display = '';
                } else {
                    option.style.display = 'none';
                }
            });
            destinationIdSelect.value = '';
        });

        // Trigger initial filtering
        sourceTypeSelect.dispatchEvent(new Event('change'));
    }

    // Handle transaction deletion
    document.querySelectorAll('.delete-transaction').forEach(function(button) {
        button.addEventListener('click', function() {
            if (!confirm('هل أنت متأكد من حذف هذه المعاملة؟')) {
                return;
            }

            const id = this.dataset.id;
            const amount = this.dataset.amount;
            const type = this.dataset.type;
            const sourceType = this.dataset.sourceType;
            const sourceId = this.dataset.sourceId;

            fetch('bank_account.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'delete_transaction',
                    transaction_id: id,
                    amount: amount,
                    transaction_type: type,
                    source_type: sourceType,
                    source_id: sourceId
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    location.reload();
                }
            })
            .catch(() => {
                alert('حدث خطأ في الاتصال بالخادم');
            });
        });
    });
});
</script>

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