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

// Every logged-in user can access their own internal mail if they have permission
if (!canView('internal')) {
    redirect('index.php');
}

$user_id = $_SESSION['user_id'];
$success = $_GET['success'] ?? '';
$error = $_GET['error'] ?? '';

// Search and filtering
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$params = [$user_id];
$where = "1=1 AND m.assigned_to = ?";

if ($search) {
    $where .= " AND (m.subject LIKE ? OR m.description LIKE ? OR u_sender.full_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Get total for pagination
$count_stmt = db()->prepare("SELECT COUNT(*) FROM internal_mail m LEFT JOIN users u_sender ON m.created_by = u_sender.id WHERE $where");
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Fetch messages
$query = "SELECT m.*, u_sender.full_name as sender_name, u_sender.profile_image as sender_image, s.name as status_name, s.color as status_color,
          (SELECT GROUP_CONCAT(display_name SEPARATOR ', ') FROM internal_attachments WHERE mail_id = m.id) as attachment_names
          FROM internal_mail m
          LEFT JOIN users u_sender ON m.created_by = u_sender.id
          LEFT JOIN mailbox_statuses s ON m.status_id = s.id
          WHERE $where
          ORDER BY m.created_at DESC
          LIMIT $limit OFFSET $offset";

$stmt = db()->prepare($query);
$stmt->execute($params);
$messages = $stmt->fetchAll();

function getStatusBadgeInternal($mail) {
    $status_name = $mail['status_name'] ?? 'received';
    $status_color = $mail['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"><i class="fas fa-inbox me-2 text-primary"></i> بريد الموظفين - الوارد</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <?php if (canAdd('internal')): ?>
        <a href="internal_outbox.php?action=compose" class="btn btn-primary shadow-sm">
            <i class="fas fa-paper-plane me-1"></i> إرسال رسالة جديدة
        </a>
        <?php endif; ?>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($success) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-white py-3">
        <form class="row g-3">
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0"><i class="fas fa-search text-muted"></i></span>
                    <input type="text" name="search" class="form-control border-start-0" placeholder="بحث في الموضوع، الرسالة، أو المرسل..." value="<?= htmlspecialchars($search) ?>">
                    <button type="submit" class="btn btn-primary">بحث</button>
                </div>
            </div>
            <?php if ($search): ?>
                <div class="col-auto">
                    <a href="internal_inbox.php" class="btn btn-outline-secondary">إعادة تعيين</a>
                </div>
            <?php endif; ?>
        </form>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4">المرسل</th>
                        <th>الموضوع</th>
                        <th>المرفقات</th>
                        <th>التاريخ</th>
                        <th>الحالة</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-plus me-1"></i>أضيف بواسطة</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-edit me-1"></i>عُدل بواسطة</th>
                        <th class="pe-4 text-center">الإجراء</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($messages): ?>
                        <?php foreach ($messages as $msg): ?>
                            <tr style="cursor: pointer;" onclick="window.location='view_mail.php?id=<?= $msg['id'] ?>&type=internal'">
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <?php if ($msg['sender_image']): ?>
                                            <img src="<?= $msg['sender_image'] ?>" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                                        <?php else: ?>
                                            <div class="rounded-circle bg-light d-flex align-items-center justify-content-center me-2" width="32" height="32" style="width:32px; height:32px;">
                                                <i class="fas fa-user text-secondary small"></i>
                                            </div>
                                        <?php endif; ?>
                                        <span class="fw-bold"><?= htmlspecialchars($msg['sender_name'] ?: 'مستخدم غير معروف') ?></span>
                                    </div>
                                </td>
                                <td>
                                    <div class="fw-bold"><?= htmlspecialchars($msg['subject']) ?></div>
                                    <small class="text-muted text-truncate d-inline-block" style="max-width: 300px;">
                                        <?= strip_tags($msg['description']) ?>
                                    </small>
                                </td>
                                <td>
                                    <?php if (!empty($msg['attachment_names'])): ?>
                                        <small class="text-muted"><i class="fas fa-paperclip me-1"></i> <?= htmlspecialchars($msg['attachment_names']) ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small class="text-muted"><?= date('Y-m-d H:i', strtotime($msg['created_at'])) ?></small>
                                </td>
                                <td><?= getStatusBadgeInternal($msg) ?></td>
                                <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($msg['created_by'] ?? null)) ?></small></td>
                            <td><small class="text-muted"><i class="fas fa-user-edit text-warning opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($msg['updated_by'] ?? null)) ?></small></td>
                            <td class="pe-4 text-center">
                                    <a href="view_mail.php?id=<?= $msg['id'] ?>&type=internal" class="btn btn-sm btn-light rounded-pill px-3">عرض</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center py-5 text-muted">
                                <i class="fas fa-envelope-open fa-3x mb-3 opacity-25"></i>
                                <p>لا توجد رسائل واردة حالياً</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php if ($total_pages > 1): ?>
    <div class="card-footer bg-white border-0 py-3">
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?><?= $search ? '&search='.urlencode($search) : '' ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

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