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

// =========================================================
// 1. التحقق من الصلاحية
// =========================================================
$allowed_roles = ['super_admin', 'ceo', 'purchasing', 'hr_manager', 'accountant'];

if (!in_array($_SESSION['role'], $allowed_roles)) {
    echo "<div class='container mt-5'><div class='alert alert-danger text-center'>⛔ عذراً، ليس لديك صلاحية للاطلاع على التقارير المالية والإحصائية.</div></div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

// =========================================================
// 2. إعداد متغيرات الفلترة
// =========================================================
$start_date = $_GET['start_date'] ?? date('Y-m-01'); // افتراضياً من أول الشهر
$end_date = $_GET['end_date'] ?? date('Y-m-d');      // إلى اليوم
$status = $_GET['status'] ?? 'all';
$payment_status = $_GET['payment_status'] ?? 'all'; // فلتر مالي جديد

// =========================================================
// 3. بناء الاستعلام وتشغيل محرك الحسابات
// =========================================================
$where_clauses = ["DATE(r.created_at) BETWEEN ? AND ?"];
$params = [$start_date, $end_date];

// فلتر الحالة الإدارية
if ($status != 'all') {
    $where_clauses[] = "r.status = ?";
    $params[] = $status;
}

// فلتر الحالة المالية
if ($payment_status != 'all') {
    $where_clauses[] = "r.payment_status = ?";
    $params[] = $payment_status;
}

$where_sql = implode(' AND ', $where_clauses);

try {
    // -------------------------------------------------------------
    // التعديل الجوهري هنا: إضافة منطق حساب القيمة (calculated_total)
    // -------------------------------------------------------------
    $sql = "SELECT 
                r.*, 
                u.username,
                u.full_name_ar, -- جلبت الاسم العربي أيضاً للعرض الأجمل
                COALESCE(d.name, r.admin_department_name) as dept_name,
                s.name as supplier_name,
                -- هنا يتم حساب المبلغ ديناميكياً بناءً على نوع الطلب
                CASE 
                    WHEN r.request_type = 'sports' THEN r.cash_allowance
                    ELSE (
                        SELECT SUM(ri.quantity * ri.unit_price) 
                        FROM request_items ri 
                        WHERE ri.request_id = r.id
                    )
                END as calculated_total
            FROM requests r
            LEFT JOIN users u ON r.user_id = u.id
            LEFT JOIN employee_details ed ON u.id = ed.user_id 
            LEFT JOIN departments d ON ed.department_id = d.id
            LEFT JOIN suppliers s ON r.supplier_id = s.id
            WHERE $where_sql
            ORDER BY r.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $requests = $stmt->fetchAll();

    // =========================================================
    // 4. حساب الإجماليات للبطاقات العلوية
    // =========================================================
    $total_all = 0;
    $total_admin = 0;
    $total_sports = 0;

    foreach ($requests as $req) {
        // نستخدم الحقل الجديد المحسوب calculated_total بدلاً من total_amount
        // نعتبر القيمة 0 إذا كانت NULL
        $amount = (float)($req['calculated_total'] ?? 0);

        // نجمع المبالغ فقط للطلبات غير المرفوضة
        if ($req['status'] != 'rejected') {
            $total_all += $amount;

            if ($req['request_type'] == 'admin') {
                $total_admin += $amount;
            } elseif ($req['request_type'] == 'sports') {
                $total_sports += $amount;
            }
        }
    }

} catch (PDOException $e) {
    echo "<div class='alert alert-danger'>خطأ في قاعدة البيانات: " . $e->getMessage() . "</div>";
    $requests = [];
}
?>

<div class="container mt-4 no-print">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-primary fw-bold"><i class="bi bi-pie-chart-fill"></i> لوحة التقارير والتحليل المالي</h3>
            <p class="text-muted">تحليل المصروفات حسب الفترة المحددة</p>
        </div>
        <button onclick="window.print()" class="btn btn-outline-dark shadow-sm">
            <i class="bi bi-printer"></i> طباعة التقرير
        </button>
    </div>

    <div class="row mb-4 g-3">
        <div class="col-md-4">
            <div class="card bg-primary text-white h-100 shadow-sm border-0">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-white-50">إجمالي قيمة الطلبات</h6>
                            <h2 class="fw-bold mb-0"><?php echo number_format($total_all, 2); ?> <small class="fs-6">AED</small></h2>
                        </div>
                        <i class="bi bi-cash-stack fs-1 text-white-50"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card bg-white border-start border-4 border-warning h-100 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted">الطلبات الإدارية</h6>
                            <h3 class="fw-bold text-dark mb-0"><?php echo number_format($total_admin, 2); ?> <small class="fs-6 text-muted">AED</small></h3>
                        </div>
                        <i class="bi bi-building fs-1 text-warning"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card bg-white border-start border-4 border-success h-100 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted">الطلبات الرياضية</h6>
                            <h3 class="fw-bold text-dark mb-0"><?php echo number_format($total_sports, 2); ?> <small class="fs-6 text-muted">AED</small></h3>
                        </div>
                        <i class="bi bi-trophy fs-1 text-success"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0 mb-4 bg-light">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label fw-bold">من تاريخ:</label>
                    <input type="date" name="start_date" class="form-control" value="<?php echo $start_date; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold">إلى تاريخ:</label>
                    <input type="date" name="end_date" class="form-control" value="<?php echo $end_date; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold">حالة الطلب:</label>
                    <select name="status" class="form-select">
                        <option value="all" <?= $status=='all'?'selected':'' ?>>الكل</option>
                        <option value="approved" <?= $status=='approved'?'selected':'' ?>>✅ معتمد</option>
                        <option value="pending" <?= $status=='pending'?'selected':'' ?>>⏳ قيد الانتظار</option>
                        <option value="rejected" <?= $status=='rejected'?'selected':'' ?>>❌ مرفوض</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold text-success">الحالة المالية:</label>
                    <select name="payment_status" class="form-select border-success">
                        <option value="all" <?= $payment_status=='all'?'selected':'' ?>>الكل</option>
                        <option value="ready_for_cheque" <?= $payment_status=='ready_for_cheque'?'selected':'' ?>>📝 بانتظار شيك</option>
                        <option value="cheque_issued" <?= $payment_status=='cheque_issued'?'selected':'' ?>>📩 شيك صادر</option>
                        <option value="paid" <?= $payment_status=='paid'?'selected':'' ?>>💰 مدفوع ومغلق</option>
                    </select>
                </div>
                <div class="col-12 text-end mt-3">
                    <a href="reports.php" class="btn btn-secondary me-2">إعادة تعيين</a>
                    <button type="submit" class="btn btn-primary px-4">تحديث النتائج <i class="bi bi-arrow-clockwise"></i></button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="container-fluid px-4">
    <div class="card shadow-sm border-0 mb-5">
        <div class="card-header bg-white py-3 d-flex justify-content-between">
            <h5 class="mb-0 text-secondary">تفاصيل السجلات (<?php echo count($requests); ?>)</h5>
            <?php if($start_date): ?>
                <small class="text-muted d-none d-print-block">الفترة: <?php echo $start_date; ?> إلى <?php echo $end_date; ?></small>
            <?php endif; ?>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-striped mb-0 text-center align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>التاريخ</th>
                            <th>مقدم الطلب</th>
                            <th>النوع</th>
                            <th>الجهة / القسم</th>
                            <th>المورد</th>
                            <th>الحالة</th>
                            <th>المالية</th>
                            <th>المبلغ (AED)</th>
                            <th class="no-print">عرض</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($requests) > 0): ?>
                            <?php foreach ($requests as $row): 
                                // تجهيز البيانات للعرض
                                $display_name = !empty($row['full_name_ar']) ? $row['full_name_ar'] : $row['username'];
                                $final_amount = (float)$row['calculated_total'];
                            ?>
                            <tr>
                                <td><?php echo $row['id']; ?></td>
                                <td><?php echo date('Y-m-d', strtotime($row['created_at'])); ?></td>
                                <td><?php echo htmlspecialchars($display_name); ?></td>
                                <td>
                                    <?php echo ($row['request_type'] == 'sports') ? '<span class="badge bg-success">رياضي</span>' : '<span class="badge bg-secondary">إداري</span>'; ?>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($row['dept_name'] ?? 'غير محدد'); ?>
                                </td>
                                <td class="text-primary">
                                    <?php echo htmlspecialchars($row['supplier_name'] ?? '-'); ?>
                                </td>
                                <td>
                                    <?php 
                                    if($row['status']=='approved') echo '<span class="badge bg-success">معتمد</span>';
                                    elseif($row['status']=='rejected') echo '<span class="badge bg-danger">مرفوض</span>';
                                    else echo '<span class="badge bg-warning text-dark">قيد الإجراء</span>';
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    if($row['payment_status']=='paid') echo '<span class="badge bg-success">مدفوع</span>';
                                    elseif($row['payment_status']=='cheque_issued') echo '<span class="badge bg-info text-dark">شيك صادر</span>';
                                    elseif($row['payment_status']=='ready_for_cheque') echo '<span class="badge bg-warning text-dark">بانتظار شيك</span>';
                                    else echo '<small class="text-muted">-</small>';
                                    ?>
                                </td>
                                <td class="fw-bold"><?php echo number_format($final_amount, 2); ?></td>
                                <td class="no-print">
                                    <a href="view_request.php?id=<?php echo $row['id']; ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="bi bi-eye"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="10" class="py-5 text-muted">لا توجد بيانات مطابقة لخيارات الفلترة الحالية.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
@media print {
    @page { size: A4 landscape; margin: 5mm; }
    .no-print { display: none !important; }
    .card { border: none !important; box-shadow: none !important; }
    .badge { border: 1px solid #000; color: #000 !important; background: none !important; padding: 2px 5px; }
    .table th { background-color: #ddd !important; color: #000 !important; -webkit-print-color-adjust: exact; }
    a { text-decoration: none; color: #000; }
    body { background-color: white !important; }
    .bg-primary { background-color: #0d6efd !important; color: white !important; -webkit-print-color-adjust: exact; }
}
</style>

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