<?php
require_once __DIR__ . '/includes/header.php';

if (!canView('expenses')) {
    redirect('index.php');
}

// Params
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-t');
$category_id = $_GET['category_id'] ?? '';
$vendor = $_GET['vendor'] ?? '';
$payment_method = $_GET['payment_method'] ?? '';

// Build Query
$sql = "SELECT e.*, c.name as category_name, u.username as created_by 
        FROM expenses e 
        LEFT JOIN expense_categories c ON e.category_id = c.id 
        LEFT JOIN users u ON e.user_id = u.id 
        WHERE e.date BETWEEN ? AND ?";
$params = [$date_from, $date_to];

if ($category_id) {
    $sql .= " AND e.category_id = ?";
    $params[] = $category_id;
}
if ($vendor) {
    $sql .= " AND e.vendor LIKE ?";
    $params[] = "%$vendor%";
}
if ($payment_method) {
    $sql .= " AND e.payment_method = ?";
    $params[] = $payment_method;
}

$sql .= " ORDER BY e.date ASC";

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

// Calculate Totals
$total_amount = 0;
$category_breakdown = [];
foreach ($expenses as $exp) {
    $total_amount += $exp['amount'];
    if (!isset($category_breakdown[$exp['category_name']])) {
        $category_breakdown[$exp['category_name']] = 0;
    }
    $category_breakdown[$exp['category_name']] += $exp['amount'];
}

// Fetch Categories
$categories = db()->query("SELECT * FROM expense_categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

?>

<style>
    @media print {
        .no-print { display: none !important; }
        .sidebar, .top-navbar { display: none !important; }
        .main-content { margin: 0 !important; padding: 0 !important; }
        .card { border: none !important; shadow: none !important; }
        body { background: white !important; }
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom no-print">
    <h1 class="h2">تقارير المصروفات</h1>
    <button onclick="window.print()" class="btn btn-outline-secondary">
        <i class="fas fa-print"></i> طباعة التقرير
    </button>
</div>

<!-- Filters -->
<div class="card shadow-sm border-0 mb-4 no-print">
    <div class="card-body bg-light">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">من تاريخ</label>
                <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">إلى تاريخ</label>
                <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">التصنيف</label>
                <select name="category_id" class="form-select">
                    <option value="">الكل</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>" <?= $category_id == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">طريقة الدفع</label>
                <select name="payment_method" class="form-select">
                    <option value="">الكل</option>
                    <option value="Cash" <?= $payment_method == 'Cash' ? 'selected' : '' ?>>نقد</option>
                    <option value="Bank Transfer" <?= $payment_method == 'Bank Transfer' ? 'selected' : '' ?>>تحويل بنكي</option>
                    <option value="Credit Card" <?= $payment_method == 'Credit Card' ? 'selected' : '' ?>>بطاقة ائتمان</option>
                    <option value="Check" <?= $payment_method == 'Check' ? 'selected' : '' ?>>شيك</option>
                </select>
            </div>
            <div class="col-md-12 text-end">
                <button type="submit" class="btn btn-primary px-4"><i class="fas fa-filter me-1"></i> عرض التقرير</button>
            </div>
        </form>
    </div>
</div>

<!-- Report Header (Print Only) -->
<div class="d-none d-print-block text-center mb-4">
    <h3>تقرير المصروفات التفصيلي</h3>
    <p class="text-muted">الفترة من <?= $date_from ?> إلى <?= $date_to ?></p>
</div>

<!-- Summary Cards -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card shadow-sm border-0 h-100 bg-primary text-white">
            <div class="card-body text-center">
                <h6 class="text-white-50 mb-2">إجمالي المصروفات</h6>
                <h2 class="fw-bold mb-0"><?= number_format($total_amount, 3) ?> ر.ع</h2>
            </div>
        </div>
    </div>
    <div class="col-md-8">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h6 class="text-muted mb-3">ملخص حسب التصنيف</h6>
                <div class="row g-2">
                    <?php foreach ($category_breakdown as $name => $amount): ?>
                        <div class="col-6 col-md-4">
                            <div class="p-2 border rounded bg-light">
                                <small class="d-block text-muted"><?= htmlspecialchars($name) ?></small>
                                <span class="fw-bold"><?= number_format($amount, 3) ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Detailed Table -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-white border-bottom py-3">
        <h5 class="mb-0">سجل العمليات</h5>
    </div>
    <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0">
            <thead class="bg-light">
                <tr>
                    <th class="ps-3">التاريخ</th>
                    <th>التصنيف</th>
                    <th>الوصف</th>
                    <th>المورد</th>
                    <th>المرجع</th>
                    <th>طريقة الدفع</th>
                    <th>بواسطة</th>
                    <th class="text-end pe-3">المبلغ</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($expenses)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4 text-muted">لا توجد بيانات للفترة المحددة</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($expenses as $exp): ?>
                        <tr>
                            <td class="ps-3"><?= $exp['date'] ?></td>
                            <td><?= htmlspecialchars($exp['category_name']) ?></td>
                            <td><?= htmlspecialchars($exp['description']) ?></td>
                            <td><?= htmlspecialchars($exp['vendor'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($exp['reference'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($exp['payment_method']) ?></td>
                            <td><small><?= htmlspecialchars($exp['created_by'] ?: '-') ?></small></td>
                            <td class="text-end pe-3 fw-bold"><?= number_format($exp['amount'], 2) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr class="bg-light fw-bold">
                        <td colspan="7" class="text-end ps-3">الإجمالي النهائي:</td>
                        <td class="text-end pe-3 text-danger"><?= number_format($total_amount, 2) ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="mt-4 text-center text-muted small d-none d-print-block">
    تم استخراج التقرير في <?= date('Y-m-d H:i:s') ?> بواسطة <?= $_SESSION['name'] ?? 'System' ?>
</div>

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