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

// Role-based routing: Admins stay here, others go to their dashboard
if (!isAdmin()) {
    redirect('user_dashboard.php');
}

$user_id = $_SESSION['user_id'];
$is_admin = isAdmin();

// Stats - Total counts from separate tables
$total_inbound = canView('inbound') ? db()->query("SELECT COUNT(*) FROM inbound_mail")->fetchColumn() : 0;
$total_outbound = canView('outbound') ? db()->query("SELECT COUNT(*) FROM outbound_mail")->fetchColumn() : 0;

// Fetch statuses for badge and count
$statuses_data = db()->query("SELECT * FROM mailbox_statuses")->fetchAll(PDO::FETCH_UNIQUE);

$in_progress_id = null;
foreach ($statuses_data as $id => $s) {
    if ($s['name'] == 'in_progress') {
        $in_progress_id = $id;
        break;
    }
}

$in_progress_count = 0;
if ($in_progress_id) {
    if (canView('inbound')) {
        $stmt = db()->prepare("SELECT COUNT(*) FROM inbound_mail WHERE status_id = ?");
        $stmt->execute([$in_progress_id]);
        $in_progress_count += $stmt->fetchColumn();
    }
    if (canView('outbound')) {
        $stmt = db()->prepare("SELECT COUNT(*) FROM outbound_mail WHERE status_id = ?");
        $stmt->execute([$in_progress_id]);
        $in_progress_count += $stmt->fetchColumn();
    }
}

// My Assignments - Combine from all tables
$my_assignments = [];
$queries = [];
if (canView('inbound')) {
    $queries[] = "SELECT id, 'inbound' as type, ref_no, subject, due_date, status_id, created_at FROM inbound_mail WHERE assigned_to = $user_id";
}
if (canView('outbound')) {
    $queries[] = "SELECT id, 'outbound' as type, ref_no, subject, due_date, status_id, created_at FROM outbound_mail WHERE assigned_to = $user_id";
}
if (canView('internal')) {
    $queries[] = "SELECT id, 'internal' as type, ref_no, subject, due_date, status_id, created_at FROM internal_mail WHERE assigned_to = $user_id";
}

if (!empty($queries)) {
    $full_query = "(" . implode(") UNION ALL (", $queries) . ") ORDER BY created_at DESC LIMIT 5";
    $stmt = db()->query($full_query);
    $my_assignments = $stmt->fetchAll();
    
    // Add status info to assignments
    foreach ($my_assignments as &$m) {
        $m['status_name'] = $statuses_data[$m['status_id']]['name'] ?? 'unknown';
        $m['status_color'] = $statuses_data[$m['status_id']]['color'] ?? '#6c757d';
    }
}

// Recent Mail (Global for Admin/Clerk, otherwise limited)
$recent_mail = [];
$recent_queries = [];
if (canView('inbound')) {
    $recent_queries[] = "SELECT m.id, 'inbound' as type, m.ref_no, m.subject, m.due_date, m.sender, m.recipient, m.status_id, m.assigned_to, m.created_by, m.date_registered, m.created_at, u.full_name as assigned_to_name
                         FROM inbound_mail m LEFT JOIN users u ON m.assigned_to = u.id";
}
if (canView('outbound')) {
    $recent_queries[] = "SELECT m.id, 'outbound' as type, m.ref_no, m.subject, m.due_date, m.sender, m.recipient, m.status_id, m.assigned_to, m.created_by, m.date_registered, m.created_at, u.full_name as assigned_to_name
                         FROM outbound_mail m LEFT JOIN users u ON m.assigned_to = u.id";
}

if (!empty($recent_queries)) {
    $full_recent_query = "(" . implode(") UNION ALL (", $recent_queries) . ")";
    
    if (!$is_admin && ($_SESSION['user_role'] ?? '') !== 'clerk') {
        $full_recent_query = "SELECT * FROM ($full_recent_query) AS combined WHERE assigned_to = $user_id OR created_by = $user_id ORDER BY created_at DESC LIMIT 10";
    } else {
        $full_recent_query = "SELECT * FROM ($full_recent_query) AS combined ORDER BY created_at DESC LIMIT 10";
    }
    
    $stmt = db()->query($full_recent_query);
    $recent_mail = $stmt->fetchAll();
    
    // Add status info
    foreach ($recent_mail as &$m) {
        $m['status_name'] = $statuses_data[$m['status_id']]['name'] ?? 'unknown';
        $m['status_color'] = $statuses_data[$m['status_id']]['color'] ?? '#6c757d';
    }
}

function getStatusBadge($mail) {
    $status_name = $mail['status_name'] ?? 'غير معروف';
    $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">لوحة التحكم الإدارية</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <?php if (canView('settings')): ?>
            <a href="charity-settings.php" class="btn btn-sm btn-outline-dark"><i class="fas fa-cog me-1"></i> الإعدادات</a>
            <?php endif; ?>
            <?php if (canAdd('inbound')): ?>
            <a href="inbound.php?action=add" class="btn btn-sm btn-outline-primary">إضافة بريد وارد</a>
            <?php endif; ?>
            <?php if (canAdd('outbound')): ?>
            <a href="outbound.php?action=add" class="btn btn-sm btn-outline-secondary">إضافة بريد صادر</a>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Overdue Alert -->
<?php 
if (canView('reports')):
    // Combine overdue counts from inbound and outbound
    $overdue_count = 0;
    $overdue_count += db()->query("SELECT COUNT(*) FROM inbound_mail WHERE due_date < CURDATE() AND status_id IN (SELECT id FROM mailbox_statuses WHERE name != 'closed')")->fetchColumn();
    $overdue_count += db()->query("SELECT COUNT(*) FROM outbound_mail WHERE due_date < CURDATE() AND status_id IN (SELECT id FROM mailbox_statuses WHERE name != 'closed')")->fetchColumn();
    
    if ($overdue_count > 0): 
    ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="alert alert-danger shadow-sm border-0 d-flex align-items-center justify-content-between mb-0">
                <div>
                    <i class="fas fa-exclamation-triangle fs-4 me-3"></i>
                    <span class="fw-bold">هناك <?= $overdue_count ?> مهام متأخرة تتطلب انتباهك!</span>
                </div>
                <a href="overdue_report.php" class="btn btn-danger btn-sm">عرض التقرير</a>
            </div>
        </div>
    </div>
    <?php 
    endif; 
endif;
?>

<!-- Stats Cards -->
<div class="row g-4 mb-4">
    <?php if (canView('inbound')): ?>
    <div class="col-md-3">
        <div class="card h-100 p-3 shadow-sm border-0 border-start border-primary border-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h6 class="text-muted mb-1">البريد الوارد</h6>
                    <h3 class="fw-bold mb-0"><?= $total_inbound ?></h3>
                </div>
                <div class="bg-primary bg-opacity-10 p-3 rounded-circle">
                    <i class="fas fa-download text-primary fs-4"></i>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (canView('outbound')): ?>
    <div class="col-md-3">
        <div class="card h-100 p-3 shadow-sm border-0 border-start border-success border-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h6 class="text-muted mb-1">البريد الصادر</h6>
                    <h3 class="fw-bold mb-0"><?= $total_outbound ?></h3>
                </div>
                <div class="bg-success bg-opacity-10 p-3 rounded-circle">
                    <i class="fas fa-upload text-success fs-4"></i>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (canView('inbound') || canView('outbound')): ?>
    <div class="col-md-3">
        <div class="card h-100 p-3 shadow-sm border-0 border-start border-info border-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h6 class="text-muted mb-1">قيد المعالجة</h6>
                    <h3 class="fw-bold mb-0"><?= $in_progress_count ?></h3>
                </div>
                <div class="bg-info bg-opacity-10 p-3 rounded-circle">
                    <i class="fas fa-clock text-info fs-4"></i>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (canView('users')): ?>
    <div class="col-md-3">
        <div class="card h-100 p-3 shadow-sm border-0 border-start border-warning border-4">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h6 class="text-muted mb-1">المستخدمين</h6>
                    <h3 class="fw-bold mb-0"><?= db()->query("SELECT COUNT(*) FROM users")->fetchColumn() ?></h3>
                </div>
                <div class="bg-warning bg-opacity-10 p-3 rounded-circle">
                    <i class="fas fa-users text-warning fs-4"></i>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php if (!empty($my_assignments)): ?>
<!-- My Assignments Section -->
<div class="card shadow-sm border-0 mb-4 bg-primary bg-opacity-10 border-top border-primary border-3">
    <div class="card-header bg-transparent py-3 border-0">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0 fw-bold text-primary"><i class="fas fa-tasks me-2"></i> مهامي الحالية</h5>
            <span class="badge bg-primary rounded-pill"><?= count($my_assignments) ?></span>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <tbody>
                    <?php foreach ($my_assignments as $mail): ?>
                        <tr style="cursor: pointer;" onclick="window.location='view_mail.php?id=<?= $mail['id'] ?>&type=<?= $mail['type'] ?>'">
                            <td class="ps-4" width="120">
                                <small class="text-muted d-block">رقم القيد</small>
                                <span class="fw-bold text-primary"><?= $mail['ref_no'] ?></span>
                            </td>
                            <td>
                                <small class="text-muted d-block">الموضوع</small>
                                <span class="fw-bold"><?= htmlspecialchars($mail['subject']) ?></span>
                            </td>
                            <td>
                                <small class="text-muted d-block">الموعد النهائي</small>
                                <?php if ($mail['due_date']): ?>
                                    <span class="<?= (strtotime($mail['due_date']) < time() && $mail['status_name'] != 'closed') ? 'text-danger fw-bold' : '' ?>">
                                        <?= $mail['due_date'] ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <small class="text-muted d-block mb-1">الحالة</small>
                                <?= getStatusBadge($mail) ?>
                            </td>
                            <td class="pe-4 text-end">
                                <i class="fas fa-chevron-left text-primary"></i>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($recent_mail)): ?>
<!-- Recent Mail -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-white py-3">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0 fw-bold"><?= $is_admin ? 'آخر المراسلات المسجلة' : 'آخر المراسلات' ?></h5>
            <a href="inbound.php" class="btn btn-sm btn-link text-decoration-none">عرض الكل</a>
        </div>
    </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>المسؤول</th>
                        <th>الحالة</th>
                        <th class="pe-4 text-center">التاريخ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_mail as $mail): ?>
                        <tr style="cursor: pointer;" onclick="window.location='view_mail.php?id=<?= $mail['id'] ?>&type=<?= $mail['type'] ?>'">
                            <td class="ps-4 fw-bold text-primary"><?= $mail['ref_no'] ?></td>
                            <td>
                                <?php if ($mail['type'] == 'inbound'): ?>
                                    <span class="text-primary"><i class="fas fa-arrow-down me-1"></i> وارد</span>
                                <?php else: ?>
                                    <span class="text-success"><i class="fas fa-arrow-up me-1"></i> صادر</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($mail['subject']) ?></td>
                            <td>
                                <?php if ($mail['due_date']): ?>
                                    <small class="<?= (strtotime($mail['due_date']) < time() && $mail['status_name'] != 'closed') ? 'text-danger fw-bold' : 'text-muted' ?>">
                                        <?= $mail['due_date'] ?>
                                    </small>
                                <?php else: ?>
                                    <small class="text-muted">-</small>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($mail['sender'] ?: $mail['recipient']) ?></td>
                            <td>
                                <?php if ($mail['assigned_to_name']): ?>
                                    <small><i class="fas fa-user-tag me-1 text-muted"></i> <?= htmlspecialchars($mail['assigned_to_name']) ?></small>
                                <?php else: ?>
                                    <small class="text-muted">غير معين</small>
                                <?php endif; ?>
                            </td>
                            <td><?= getStatusBadge($mail) ?></td>
                            <td class="pe-4 text-center"><?= date('Y-m-d', strtotime($mail['date_registered'])) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

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