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

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

$type_filter = $_GET['type'] ?? '';
$user_filter = $_GET['user_id'] ?? '';

$overdue_items = [];
$queries = [];

if (!$type_filter || $type_filter === 'inbound') {
    $where = ["m.due_date < CURDATE()", "s.name != 'closed'"];
    $params = [];
    if ($user_filter) {
        $where[] = "m.assigned_to = ?";
        $params[] = $user_filter;
    }
    $where_clause = implode(" AND ", $where);
    $sql = "SELECT m.*, 'inbound' as type, u.full_name as assigned_name, s.name as status_name, s.color as status_color
            FROM inbound_mail m 
            LEFT JOIN users u ON m.assigned_to = u.id 
            LEFT JOIN mailbox_statuses s ON m.status_id = s.id
            WHERE $where_clause";
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $overdue_items = array_merge($overdue_items, $stmt->fetchAll());
}

if (!$type_filter || $type_filter === 'outbound') {
    $where = ["m.due_date < CURDATE()", "s.name != 'closed'"];
    $params = [];
    if ($user_filter) {
        $where[] = "m.assigned_to = ?";
        $params[] = $user_filter;
    }
    $where_clause = implode(" AND ", $where);
    $sql = "SELECT m.*, 'outbound' as type, u.full_name as assigned_name, s.name as status_name, s.color as status_color
            FROM outbound_mail m 
            LEFT JOIN users u ON m.assigned_to = u.id 
            LEFT JOIN mailbox_statuses s ON m.status_id = s.id
            WHERE $where_clause";
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $overdue_items = array_merge($overdue_items, $stmt->fetchAll());
}

// Sort by due date
usort($overdue_items, function($a, $b) {
    return strtotime($a['due_date']) - strtotime($b['due_date']);
});

// Fetch all users for filter
$users = db()->query("SELECT id, full_name FROM users ORDER BY full_name")->fetchAll();

function getStatusBadgeForReport($item) {
    $status_name = $item['status_name'] ?? 'غير معروف';
    $status_color = $item['status_color'] ?? '#6c757d';
    
    $display_name = $status_name;
    if ($status_name == 'received') $display_name = 'تم الاستلام';
    if ($status_name == 'in_progress') $display_name = 'قيد المعالجة';
    if ($status_name == 'closed') $display_name = 'مكتمل';
    
    return '<span class="badge" style="background-color: ' . $status_color . ';">' . htmlspecialchars($display_name) . '</span>';
}
?>

<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>
</div>

<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">نوع البريد</label>
                <select name="type" class="form-select">
                    <option value="">الكل</option>
                    <option value="inbound" <?= $type_filter == 'inbound' ? 'selected' : '' ?>>وارد</option>
                    <option value="outbound" <?= $type_filter == 'outbound' ? 'selected' : '' ?>>صادر</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">الموظف المسؤول</label>
                <select name="user_id" class="form-select">
                    <option value="">الكل</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?= $user['id'] ?>" <?= $user_filter == $user['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($user['full_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">تصفية</button>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header bg-danger text-white">
        <h5 class="card-title mb-0"><i class="fas fa-exclamation-triangle me-2"></i> جميع المهام المتأخرة</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>رقم المرجع</th>
                        <th>النوع</th>
                        <th>الموضوع</th>
                        <th>الموظف المسؤول</th>
                        <th>الحالة</th>
                        <th>تاريخ الاستحقاق</th>
                        <th>الأيام المتأخرة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($overdue_items)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4 text-muted">لا توجد مهام متأخرة حالياً.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($overdue_items as $item): 
                            $due_date = new DateTime($item['due_date']);
                            $today = new DateTime();
                            $diff = $today->diff($due_date)->format("%a");
                        ?>
                            <tr>
                                <td class="fw-bold"><?= htmlspecialchars($item['ref_no']) ?></td>
                                <td>
                                    <span class="badge bg-<?= $item['type'] == 'inbound' ? 'info' : 'warning' ?>">
                                        <?= $item['type'] == 'inbound' ? 'وارد' : 'صادر' ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($item['subject']) ?></td>
                                <td><?= htmlspecialchars($item['assigned_name'] ?? 'غير معين') ?></td>
                                <td><?= getStatusBadgeForReport($item) ?></td>
                                <td class="text-danger fw-bold"><?= $item['due_date'] ?></td>
                                <td class="text-danger fw-bold"><?= $diff ?> يوم</td>
                                <td>
                                    <a href="view_mail.php?id=<?= $item['id'] ?>&type=<?= $item['type'] ?>" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye"></i> عرض
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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