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

// Check if user has view permission
if (!isLoggedIn()) {
    redirect('login.php');
}

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

// Stats for this specific user - Combine from all tables
$my_total_assignments = 0;
$my_pending_tasks = 0;

foreach (['inbound', 'outbound', 'internal'] as $t) {
    if (canView($t)) {
        $table = $t . '_mail';
        $stmt = db()->prepare("SELECT COUNT(*) FROM $table WHERE assigned_to = ?");
        $stmt->execute([$user_id]);
        $my_total_assignments += $stmt->fetchColumn();

        $stmt = db()->prepare("SELECT COUNT(*) FROM $table WHERE assigned_to = ? AND status_id IN (SELECT id FROM mailbox_statuses WHERE name != 'closed')");
        $stmt->execute([$user_id]);
        $my_pending_tasks += $stmt->fetchColumn();
    }
}

// Global Stats
$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);

// My Assignments
$my_assignments = [];
$assignment_queries = [];
if (canView('inbound')) $assignment_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')) $assignment_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')) $assignment_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($assignment_queries)) {
    $full_assignment_query = "(" . implode(") UNION ALL (", $assignment_queries) . ") ORDER BY created_at DESC LIMIT 10";
    $stmt = db()->query($full_assignment_query);
    $my_assignments = $stmt->fetchAll();
    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 Activity
$recent_activity = [];
$recent_queries = [];
if (canView('inbound')) $recent_queries[] = "SELECT id, 'inbound' as type, ref_no, subject, status_id, created_by, assigned_to, updated_at FROM inbound_mail";
if (canView('outbound')) $recent_queries[] = "SELECT id, 'outbound' as type, ref_no, subject, status_id, created_by, assigned_to, updated_at FROM outbound_mail";
if (canView('internal')) $recent_queries[] = "SELECT id, 'internal' as type, ref_no, subject, status_id, created_by, assigned_to, updated_at FROM internal_mail";

if (!empty($recent_queries)) {
    $full_recent_query = "(" . implode(") UNION ALL (", $recent_queries) . ")";
    
    if ($is_admin || $is_clerk) {
        $full_recent_query = "SELECT * FROM ($full_recent_query) AS combined WHERE (type != 'internal' OR assigned_to = $user_id OR created_by = $user_id) ORDER BY updated_at DESC LIMIT 10";
    } else {
        $full_recent_query = "SELECT * FROM ($full_recent_query) AS combined WHERE (assigned_to = $user_id OR created_by = $user_id) ORDER BY updated_at DESC LIMIT 10";
    }
    
    $stmt = db()->query($full_recent_query);
    $recent_activity = $stmt->fetchAll();
    foreach ($recent_activity as &$a) {
        $a['status_name'] = $statuses_data[$a['status_id']]['name'] ?? 'unknown';
        $a['status_color'] = $statuses_data[$a['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="row mb-4">
    <div class="col-md-12">
        <div class="card bg-dark text-white p-4 shadow-lg border-0 overflow-hidden position-relative">
            <div class="position-absolute end-0 top-0 p-3 opacity-10">
                <i class="fas fa-envelope-open-text fa-10x" style="transform: rotate(-15deg);"></i>
            </div>
            <div class="d-flex justify-content-between align-items-center position-relative">
                <div>
                    <h2 class="fw-bold mb-1">مرحباً، <?= htmlspecialchars($current_user['full_name'] ?? $_SESSION['name']) ?>!</h2>
                    <p class="mb-0 opacity-75">
                        أنت مسجل كـ <strong>
                        <?php 
                        if ($is_admin) echo 'مدير النظام';
                        elseif ($is_clerk) echo 'كاتب';
                        else echo 'موظف';
                        ?>
                        </strong>. 
                        <?php if ($is_admin || $is_clerk): ?>
                            يمكنك متابعة كافة المراسلات وإدارة المهام.
                        <?php else: ?>
                            تابع مهامك المسندة إليك هنا.
                        <?php endif; ?>
                    </p>
                </div>
                <div class="d-none d-md-block">
                    <?php if ($current_user['profile_image']): ?>
                        <img src="<?= $current_user['profile_image'] ?>?v=<?= time() ?>" alt="Profile" class="rounded-circle border border-3 border-white shadow" style="width: 100px; height: 100px; object-fit: cover;">
                    <?php else: ?>
                        <div class="bg-white bg-opacity-25 rounded-circle d-flex align-items-center justify-content-center border border-3 border-white shadow" style="width: 100px; height: 100px;">
                            <i class="fas fa-user fa-3x text-white"></i>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <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">
                <div class="bg-primary bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-tasks text-primary fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">مهامي</h6>
                    <h3 class="fw-bold mb-0"><?= $my_total_assignments ?></h3>
                </div>
            </div>
        </div>
    </div>
    <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">
                <div class="bg-warning bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-clock text-warning fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">قيد التنفيذ</h6>
                    <h3 class="fw-bold mb-0"><?= $my_pending_tasks ?></h3>
                </div>
            </div>
        </div>
    </div>

    <?php if ($is_admin || $is_clerk): ?>
    <?php if (canView('inbound')): ?>
    <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">
                <div class="bg-info bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-download text-info fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">إجمالي الوارد</h6>
                    <h3 class="fw-bold mb-0"><?= $total_inbound ?></h3>
                </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">
                <div class="bg-success bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-upload text-success fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">إجمالي الصادر</h6>
                    <h3 class="fw-bold mb-0"><?= $total_outbound ?></h3>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <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">
                <div class="bg-info bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-envelope-open text-info fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">وارد من قبلي</h6>
                    <?php
                    $my_in_count = db()->prepare("SELECT COUNT(*) FROM inbound_mail WHERE created_by = ?");
                    $my_in_count->execute([$user_id]);
                    $my_in_count = $my_in_count->fetchColumn();
                    ?>
                    <h3 class="fw-bold mb-0"><?= $my_in_count ?></h3>
                </div>
            </div>
        </div>
    </div>
    <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">
                <div class="bg-success bg-opacity-10 p-3 rounded-3 me-3">
                    <i class="fas fa-paper-plane text-success fs-4"></i>
                </div>
                <div>
                    <h6 class="text-muted mb-1">صادر من قبلي</h6>
                    <?php
                    $my_out_count = db()->prepare("SELECT COUNT(*) FROM outbound_mail WHERE created_by = ?");
                    $my_out_count->execute([$user_id]);
                    $my_out_count = $my_out_count->fetchColumn();
                    ?>
                    <h3 class="fw-bold mb-0"><?= $my_out_count ?></h3>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0 mb-4 h-100">
            <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold"><i class="fas fa-clipboard-list me-2 text-primary"></i> مهامي المسندة</h5>
                <div class="btn-group">
                    <?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-success">إضافة صادر</a>
                    <?php endif; ?>
                </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 class="pe-4 text-center">الإجراء</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($my_assignments)): ?>
                                <?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 fw-bold text-primary"><?= $mail['ref_no'] ?></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><?= getStatusBadge($mail) ?></td>
                                        <td class="pe-4 text-center">
                                            <a href="view_mail.php?id=<?= $mail['id'] ?>&type=<?= $mail['type'] ?>" class="btn btn-sm btn-light rounded-pill px-3">عرض</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center py-5 text-muted">
                                        أنت على اطلاع بكافة مهامك! لا توجد مهام معلقة.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-0 mb-4 h-100">
            <div class="card-header bg-white py-3 border-bottom">
                <h5 class="mb-0 fw-bold"><i class="fas fa-bell me-2 text-warning"></i> <?= ($is_admin || $is_clerk) ? 'آخر المراسلات' : 'نشاطاتي الأخيرة' ?></h5>
            </div>
            <div class="card-body p-0" style="max-height: 500px; overflow-y: auto;">
                <div class="list-group list-group-flush">
                    <?php if (!empty($recent_activity)): ?>
                        <?php foreach ($recent_activity as $act): ?>
                            <a href="view_mail.php?id=<?= $act['id'] ?>&type=<?= $act['type'] ?>" class="list-group-item list-group-item-action p-3 border-0 border-bottom">
                                <div class="d-flex w-100 justify-content-between mb-1">
                                    <h6 class="mb-1 fw-bold text-truncate" title="<?= htmlspecialchars($act['subject']) ?>"><?= htmlspecialchars($act['subject']) ?></h6>
                                    <small class="text-muted"><?= date('m-d', strtotime($act['updated_at'])) ?></small>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="fas <?= $act['type'] == 'inbound' ? 'fa-arrow-down text-primary' : ($act['type'] == 'outbound' ? 'fa-arrow-up text-success' : 'fa-exchange-alt text-info') ?> me-1"></i>
                                        <?= $act['ref_no'] ?>
                                    </small>
                                    <?= getStatusBadge($act) ?>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center py-5 text-muted">
                            لا يوجد نشاط مسجل
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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