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

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

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

// Get date range from parameters
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Get transactions within the date range
$query = "
    SELECT 
        ft.id,
        ft.type,
        ft.amount,
        ft.description,
        ft.transaction_date,
        ft.account_type,
        ft.account_id,
        ft.transfer_to_type,
        ft.transfer_to_id,
        ft.category_id,
        c.name as category_name,
        CASE 
            WHEN ft.account_type = 'cash' THEN cf.name
            WHEN ft.account_type = 'bank' THEN ba.bank_name
            ELSE NULL
        END as account_name,
        CASE 
            WHEN ft.transfer_to_type = 'cash' THEN cf_to.name
            WHEN ft.transfer_to_type = 'bank' THEN ba_to.bank_name
            ELSE NULL
        END as transfer_to_name
    FROM financial_transactions ft
    LEFT JOIN categories c ON ft.category_id = c.id
    LEFT JOIN cash_funds cf ON ft.account_type = 'cash' AND ft.account_id = cf.id
    LEFT JOIN bank_accounts ba ON ft.account_type = 'bank' AND ft.account_id = ba.id
    LEFT JOIN cash_funds cf_to ON ft.transfer_to_type = 'cash' AND ft.transfer_to_id = cf_to.id
    LEFT JOIN bank_accounts ba_to ON ft.transfer_to_type = 'bank' AND ft.transfer_to_id = ba_to.id
    WHERE ft.transaction_date BETWEEN ? AND ?
    ORDER BY ft.transaction_date DESC";

$stmt = $db->prepare($query);
$stmt->execute([$start_date, $end_date]);
$transactions = $stmt->fetchAll();

// Calculate totals
$total_income = 0;
$total_expense = 0;
foreach ($transactions as $transaction) {
    if ($transaction['type'] === 'income') {
        $total_income += $transaction['amount'];
    } elseif ($transaction['type'] === 'expense') {
        $total_expense += $transaction['amount'];
    }
}
$net_balance = $total_income - $total_expense;

// Get association settings
$stmt = $db->query("SELECT * FROM association_settings WHERE id = 1");
$settings = $stmt->fetch();
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<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">
    <style>
        @media print {
            @page {
                size: A4;
                margin: 1.5cm;
            }
            body {
                font-size: 12pt;
            }
            .table {
                width: 100%;
                margin-bottom: 1rem;
                border-collapse: collapse;
            }
            .table th,
            .table td {
                padding: 0.5rem;
                border: 1px solid #dee2e6;
            }
            .no-print {
                display: none !important;
            }
        }
        .text-success {
            color: #28a745 !important;
        }
        .text-danger {
            color: #dc3545 !important;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- Print Header -->
        <?php echo get_print_header("كشف المعاملات المالية"); ?>

        <!-- Date Range -->
        <div class="row mb-3">
            <div class="col">
                <p>الفترة: من <?php echo date('Y/m/d', strtotime($start_date)); ?> إلى <?php echo date('Y/m/d', strtotime($end_date)); ?></p>
            </div>
        </div>

        <!-- Financial Summary -->
        <div class="row mb-4">
            <div class="col">
                <table class="table table-bordered">
                    <tr>
                        <th>مجموع المداخيل</th>
                        <td class="text-success"><?php echo number_format($total_income, 2); ?> درهم</td>
                    </tr>
                    <tr>
                        <th>مجموع المصاريف</th>
                        <td class="text-danger"><?php echo number_format($total_expense, 2); ?> درهم</td>
                    </tr>
                    <tr>
                        <th>الرصيد الصافي</th>
                        <td class="<?php echo $net_balance >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($net_balance, 2); ?> درهم
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- Transactions Table -->
        <div class="row">
            <div class="col">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>التاريخ</th>
                            <th>النوع</th>
                            <th>المبلغ</th>
                            <th>الحساب</th>
                            <th>التصنيف</th>
                            <th>الوصف</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 'مدخول';
                                        break;
                                    case 'expense':
                                        echo 'مصروف';
                                        break;
                                    case 'transfer':
                                        echo 'تحويل';
                                        break;
                                }
                                ?>
                            </td>
                            <td class="<?php echo $transaction['type'] === 'income' ? 'text-success' : 'text-danger'; ?>">
                                <?php echo number_format($transaction['amount'], 2); ?> درهم
                            </td>
                            <td>
                                <?php
                                if ($transaction['type'] === 'transfer') {
                                    echo htmlspecialchars($transaction['account_name']) . ' ➜ ' . htmlspecialchars($transaction['transfer_to_name']);
                                } else {
                                    echo htmlspecialchars($transaction['account_name']);
                                }
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($transaction['category_name'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Print Button -->
        <div class="row mb-4 no-print">
            <div class="col">
                <button onclick="window.print()" class="btn btn-primary">
                    <i class="fas fa-print"></i> طباعة
                </button>
                <button onclick="window.close()" class="btn btn-secondary">
                    إغلاق
                </button>
            </div>
        </div>
    </div>

    <script>
    // Automatically open print dialog when the page loads
    window.onload = function() {
        if (!window.location.hash) {
            window.print();
        }
    }
    </script>
</body>
</html>
