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

$id = $_GET['id'] ?? 0;
$type = $_GET['type'] ?? '';

if (!$id) redirect('index.php');

// If type is not provided, try to find it in any of the tables (for backward compatibility if any links were missed)
if (!$type) {
    foreach (['inbound', 'outbound', 'internal'] as $t) {
        $table = $t . '_mail';
        $check = db()->prepare("SELECT id FROM $table WHERE id = ?");
        $check->execute([$id]);
        if ($check->fetch()) {
            $type = $t;
            break;
        }
    }
}

if (!$type) redirect('index.php');

$table_mail = $type . '_mail';
$table_attachments = $type . '_attachments';
$table_comments = $type . '_comments';

$stmt = db()->prepare("SELECT m.*, u1.full_name as assigned_name, u2.full_name as creator_name, 
                             s.name as status_name, s.color as status_color 
                      FROM $table_mail m 
                      LEFT JOIN users u1 ON m.assigned_to = u1.id 
                      LEFT JOIN users u2 ON m.created_by = u2.id 
                      LEFT JOIN mailbox_statuses s ON m.status_id = s.id 
                      WHERE m.id = ?");
$stmt->execute([$id]);
$mail = $stmt->fetch();

if (!$mail) redirect('index.php');

// Add back the type for logic below
$mail['type'] = $type;

// Check if user has view permission for this mail type
if (!canView($type)) {
    redirect('index.php');
}

// Security check for internal mail: only sender or recipient can view
if ($type === 'internal') {
    if ($mail['created_by'] != $_SESSION['user_id'] && $mail['assigned_to'] != $_SESSION['user_id']) {
        redirect('internal_inbox.php');
    }
}

$success = '';
$error = '';

// Handle Comment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_comment'])) {
    if ($type !== 'internal' && !canEdit($type)) {
        $error = 'عذراً، ليس لديك الصلاحية لإضافة تعليقات';
    } else {
        $comment = $_POST['comment'] ?? '';
        $referred_user_id = $_POST['referred_user_id'] ?: null;
        
        if ($comment) {
            $stmt = db()->prepare("INSERT INTO $table_comments (mail_id, user_id, comment, referred_user_id) VALUES (?, ?, ?, ?)");
            $stmt->execute([$id, $_SESSION['user_id'], $comment, $referred_user_id]);
            
            // Send email notification if referred
            if ($referred_user_id) {
                $stmt_u = db()->prepare("SELECT email, full_name FROM users WHERE id = ?");
                $stmt_u->execute([$referred_user_id]);
                $referred_user = $stmt_u->fetch();
                
                if ($referred_user && !empty($referred_user['email'])) {
                    $sender_name = $_SESSION['name'] ?? 'زميلك';
                    $mail_subject = "إحالة بريد: " . $mail['subject'];
                    $mail_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . "/view_mail.php?id=" . $id . "&type=" . $type;
                    
                    $html = "
                        <div dir='rtl'>
                        <h3>مرحباً " . htmlspecialchars($referred_user['full_name']) . "</h3>
                        <p>قام <strong>" . htmlspecialchars($sender_name) . "</strong> بإحالة بريد إليك مع التعليق التالي:</p>
                        <blockquote style='background: #f9f9f9; padding: 10px; border-left: 5px solid #ccc;'>
                            " . nl2br(htmlspecialchars($comment)) . "
                        </blockquote>
                        <p><strong>تفاصيل البريد:</strong></p>
                        <ul>
                            <li><strong>رقم القيد:</strong> " . htmlspecialchars($mail['ref_no']) . "</li>
                            <li><strong>الموضوع:</strong> " . htmlspecialchars($mail['subject']) . "</li>
                        </ul>
                        <p><a href='{$mail_link}' style='display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;'>عرض البريد</a></p>
                        </div>
                    ";
                    
                    $txt = "قام {$sender_name} بإحالة بريد إليك: {$mail['subject']}\n\nالتعليق: {$comment}\n\nعرض البريد: {$mail_link}";
                    
                    MailService::sendMail($referred_user['email'], $mail_subject, $html, $txt);
                }
            }
            
            $_SESSION['success'] = 'تم إضافة التعليق بنجاح';
            redirect("view_mail.php?id=$id&type=$type");
        }
    }
}

// Handle Attachment upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['attachment'])) {
    if ($type !== 'internal' && !canEdit($type)) {
        $error = 'عذراً، ليس لديك الصلاحية لرفع مرفقات';
    } else {
        $file = $_FILES['attachment'];
        $display_name = $_POST['display_name'] ?? '';
        if ($file['error'] === 0) {
            $upload_dir = 'uploads/attachments/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $file_name = time() . '_' . basename($file['name']);
            $target_path = $upload_dir . $file_name;
            
            if (move_uploaded_file($file['tmp_name'], $target_path)) {
                $stmt = db()->prepare("INSERT INTO $table_attachments (mail_id, display_name, file_path, file_name, file_size) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$id, $display_name, $target_path, $file['name'], $file['size']]);
                $_SESSION['success'] = 'تم رفع الملف بنجاح';
                redirect("view_mail.php?id=$id&type=$type");
            } else {
                $error = 'فشل في رفع الملف';
            }
        }
    }
}

// Handle Attachment deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_attachment'])) {
    if ($type !== 'internal' && !canDelete($type)) {
        $error = 'عذراً، ليس لديك الصلاحية لحذف المرفقات';
    } else {
        $attachment_id = $_POST['attachment_id'] ?? 0;
        if ($attachment_id) {
            $stmt = db()->prepare("SELECT * FROM $table_attachments WHERE id = ?");
            $stmt->execute([$attachment_id]);
            $attachment = $stmt->fetch();
            
            if ($attachment) {
                if (file_exists($attachment['file_path'])) {
                    unlink($attachment['file_path']);
                }
                $stmt = db()->prepare("DELETE FROM $table_attachments WHERE id = ?");
                $stmt->execute([$attachment_id]);
                $_SESSION['success'] = 'تم حذف المرفق بنجاح';
                redirect("view_mail.php?id=$id&type=$type");
            }
        }
    }
}

// Get session messages
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
    $error = $_SESSION['error'];
    unset($_SESSION['error']);
}

$comments_stmt = db()->prepare("SELECT c.*, u.full_name, ru.full_name as referred_name 
                            FROM $table_comments c 
                            LEFT JOIN users u ON c.user_id = u.id 
                            LEFT JOIN users ru ON c.referred_user_id = ru.id
                            WHERE c.mail_id = ? ORDER BY c.created_at DESC");
$comments_stmt->execute([$id]);
$mail_comments = $comments_stmt->fetchAll();

$attachments_stmt = db()->prepare("SELECT * FROM $table_attachments WHERE mail_id = ? ORDER BY created_at DESC");
$attachments_stmt->execute([$id]);
$mail_attachments = $attachments_stmt->fetchAll();

// Fetch all users for referral dropdown
$stmt_users = db()->prepare("SELECT id, full_name, role FROM users WHERE id != ? ORDER BY full_name ASC");
$stmt_users->execute([$_SESSION['user_id']]);
$all_users = $stmt_users->fetchAll();

function isPreviewable($fileName) {
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    return in_array($ext, ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'webp']);
}

$type_label = 'بريد وارد';
if ($type == 'outbound') $type_label = 'بريد صادر';
if ($type == 'internal') $type_label = 'رسالة داخلية';

$back_link = $type . '.php';
if ($type == 'internal') {
    $back_link = ($mail['created_by'] == $_SESSION['user_id']) ? 'internal_outbox.php' : 'internal_inbox.php';
}
?>

<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">تفاصيل <?= $type_label ?></h1>
    <div class="btn-group">
        <a href="<?= $back_link ?>" class="btn btn-outline-secondary">عودة للقائمة</a>
        <?php if ($type !== 'internal' && canEdit($type)): ?>
        <a href="<?= $type ?>.php?action=edit&id=<?= $mail['id'] ?>" class="btn btn-outline-primary">تعديل البيانات</a>
        <?php if ($type === 'outbound'): ?>
        <a href="print_outbound.php?id=<?= $mail['id'] ?>" target="_blank" class="btn btn-outline-secondary"><i class="fas fa-print me-1"></i> طباعة</a>
        <?php elseif ($type === 'inbound'): ?>
        <a href="print_inbound.php?id=<?= $mail['id'] ?>" target="_blank" class="btn btn-outline-secondary"><i class="fas fa-print me-1"></i> طباعة</a>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

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

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

<div class="row">
    <!-- Mail Details -->
    <div class="col-md-8">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">المعلومات الأساسية</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="text-muted small">رقم القيد</label>
                        <p class="fw-bold fs-5 text-primary"><?= $mail['ref_no'] ?></p>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">تاريخ التسجيل</label>
                        <p class="fw-bold"><?= $mail['date_registered'] ?></p>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">الموعد النهائي</label>
                        <p class="fw-bold">
                            <?php if ($mail['due_date']): ?>
                                <span class="<?= (strtotime($mail['due_date']) < time() && $mail['status_name'] != 'closed') ? 'text-danger' : '' ?>">
                                    <?= $mail['due_date'] ?>
                                    <?php if (strtotime($mail['due_date']) < time() && $mail['status_name'] != 'closed'): ?>
                                        <i class="fas fa-exclamation-triangle ms-1"></i>
                                    <?php endif; ?>
                                </span>
                            <?php else: ?>
                                <span class="text-muted">غير محدد</span>
                            <?php endif; ?>
                        </p>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">الحالة</label>
                        <p>
                            <?php 
                            $s_name = $mail['status_name'] ?? 'received';
                            $s_color = $mail['status_color'] ?? '#6c757d';
                            $d_name = $s_name;
                            if ($s_name == 'received') $d_name = ($type == 'internal' ? 'جديد / مرسل' : 'تم الاستلام');
                            if ($s_name == 'in_progress') $d_name = 'قيد المعالجة';
                            if ($s_name == 'closed') $d_name = ($type == 'internal' ? 'مؤرشف' : 'مكتمل');
                            ?>
                            <span class="badge" style="background-color: <?= $s_color ?>;"><?= htmlspecialchars($d_name) ?></span>
                        </p>
                    </div>
                    <div class="col-12">
                        <label class="text-muted small">الموضوع</label>
                        <div class="fw-bold">
                            <?php 
                            if ($type == 'outbound' || $type == 'internal') {
                                echo $mail['subject'];
                            } else {
                                echo htmlspecialchars($mail['subject']);
                            }
                            ?>
                        </div>
                    </div>
                    
                    <?php if ($type == 'internal'): ?>
                    <div class="col-md-6">
                        <label class="text-muted small">المرسل</label>
                        <p class="fw-bold text-primary"><?= htmlspecialchars($mail['creator_name']) ?></p>
                    </div>
                    <div class="col-md-6">
                        <label class="text-muted small">المستلم</label>
                        <p class="fw-bold text-success"><?= htmlspecialchars($mail['assigned_name']) ?></p>
                    </div>
                    <?php else: ?>
                    <div class="col-md-6">
                        <label class="text-muted small"><?= $type == 'inbound' ? 'المرسل' : 'المرسل الداخلي' ?></label>
                        <p><?= htmlspecialchars($mail['sender'] ?: 'غير محدد') ?></p>
                    </div>
                    <div class="col-md-6">
                        <label class="text-muted small"><?= $type == 'inbound' ? 'المستلم الداخلي' : 'الجهة المستلمة' ?></label>
                        <p><?= htmlspecialchars($mail['recipient'] ?: 'غير محدد') ?></p>
                    </div>
                    <?php endif; ?>

                    <div class="col-12">
                        <label class="text-muted small">الرسالة / الوصف</label>
                        <div class="bg-light p-3 rounded border">
                            <?php 
                            echo $mail['description'] ?: '<span class="text-muted">لا يوجد محتوى إضافي</span>';
                            ?>
                        </div>
                    </div>
                    
                    <?php if ($type != 'internal'): ?>
                    <div class="col-md-6">
                        <label class="text-muted small">الموظف المسؤول</label>
                        <p><?= htmlspecialchars($mail['assigned_name'] ?: 'غير معين') ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <div class="col-md-6 <?= $type == 'internal' ? 'col-md-12' : '' ?> text-end">
                        <label class="text-muted small">تاريخ الإنشاء</label>
                        <p class="text-muted small"><?= $mail['created_at'] ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Comments -->
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">الردود والمتابعة</h5>
            </div>
            <div class="card-body">
                <?php if ($type === 'internal' || canEdit($type)): ?>
                <form method="POST" class="mb-4 bg-light p-3 rounded border">
                    <div class="mb-2">
                        <label class="form-label small fw-bold">إضافة <?= $type == 'internal' ? 'رد' : 'تعليق' ?></label>
                        <textarea name="comment" class="form-control" rows="2" placeholder="اكتب ردك هنا..." required></textarea>
                    </div>
                    <?php if ($type != 'internal'): ?>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">إحالة إلى موظف (اختياري)</label>
                        <select name="referred_user_id" class="form-select form-select-sm">
                            <option value="">-- اختر موظفاً للإحالة --</option>
                            <?php foreach ($all_users as $u): ?>
                                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['full_name']) ?> (<?= ucfirst($u['role']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    <button type="submit" name="add_comment" class="btn btn-sm btn-primary">إرسال <?= $type == 'internal' ? 'الرد' : 'التعليق' ?></button>
                </form>
                <?php endif; ?>

                <div class="comment-list">
                    <?php if ($mail_comments): foreach ($mail_comments as $c): ?>
                        <div class="border-bottom pb-2 mb-2">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <span class="fw-bold text-primary"><?= htmlspecialchars($c['full_name']) ?></span>
                                    <?php if ($c['referred_name']): ?>
                                        <span class="badge bg-info text-dark ms-2 small">
                                            <i class="fas fa-share ms-1"></i> إحالة إلى: <?= htmlspecialchars($c['referred_name']) ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <span class="text-muted small"><?= $c['created_at'] ?></span>
                            </div>
                            <p class="mb-0 small"><?= nl2br(htmlspecialchars($c['comment'])) ?></p>
                        </div>
                    <?php endforeach; else: ?>
                        <p class="text-center text-muted small">لا توجد ردود بعد</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Attachments Side -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">المرفقات</h5>
            </div>
            <div class="card-body">
                <?php if ($type === 'internal' || canEdit($type)): ?>
                <form method="POST" enctype="multipart/form-data" class="mb-4">
                    <div class="mb-2">
                        <label class="form-label small mb-1">اسم المرفق (يظهر في القائمة)</label>
                        <input type="text" name="display_name" class="form-control form-control-sm mb-2" placeholder="مثال: صورة، مستند...">
                        <label class="form-label small mb-1">اختر الملف</label>
                        <input type="file" name="attachment" class="form-control form-control-sm" required>
                    </div>
                    <button type="submit" class="btn btn-sm btn-secondary w-100">رفع ملف</button>
                </form>
                <?php endif; ?>

                <div class="list-group list-group-flush">
                    <?php if ($mail_attachments): foreach ($mail_attachments as $a): ?>
                        <div class="list-group-item px-0">
                            <div class="d-flex w-100 justify-content-between align-items-center">
                                <div class="text-truncate" style="max-width: 150px;">
                                    <i class="fas fa-file me-2 text-muted"></i>
                                    <a href="<?= $a['file_path'] ?>" target="_blank" class="text-decoration-none small">
                                        <?= htmlspecialchars($a['display_name'] ?: $a['file_name']) ?>
                                    </a>
                                </div>
                                <div class="d-flex align-items-center">
                                    <span class="text-muted small me-2"><?= round($a['file_size'] / 1024, 1) ?> KB</span>
                                    <?php if (isPreviewable($a['file_name'])): ?>
                                        <button class="btn btn-link btn-sm p-0 text-primary preview-btn me-2" 
                                                data-file="<?= $a['file_path'] ?>" 
                                                data-name="<?= htmlspecialchars($a['display_name'] ?: $a['file_name']) ?>"
                                                title="معاينة">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($type == 'internal' || canDelete($type)): ?>
                                    <form method="POST" class="d-inline delete-attachment-form">
                                        <input type="hidden" name="attachment_id" value="<?= $a['id'] ?>">
                                        <input type="hidden" name="delete_attachment" value="1">
                                        <button type="button" class="btn btn-link btn-sm p-0 text-danger delete-btn" title="حذف">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; else: ?>
                        <p class="text-center text-muted small py-3">لا توجد مرفقات</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="previewModalLabel">معاينة الملف</h5>
                <button type="button" class="btn-close ms-0 me-auto" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0 bg-dark d-flex align-items-center justify-content-center" style="min-height: 80vh;">
                <div id="previewContainer" class="w-100 h-100 text-center"></div>
            </div>
            <div class="modal-footer">
                <a id="downloadBtn" href="#" class="btn btn-primary" download>تحميل الملف</a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
            </div>
        </div>
    </div>
</div>

<script>
    const previewModalEl = document.getElementById('previewModal');
    let previewModal;
    if (typeof bootstrap !== 'undefined') {
        previewModal = new bootstrap.Modal(previewModalEl);
    }
    const previewContainer = document.getElementById('previewContainer');
    const previewModalLabel = document.getElementById('previewModalLabel');
    const downloadBtn = document.getElementById('downloadBtn');

    document.querySelectorAll('.preview-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const filePath = this.getAttribute('data-file');
            const fileName = this.getAttribute('data-name');
            const ext = filePath.split('.').pop().toLowerCase();
            
            previewModalLabel.textContent = 'معاينة: ' + fileName;
            downloadBtn.href = filePath;
            previewContainer.innerHTML = '';
            
            if (ext === 'pdf') {
                previewContainer.innerHTML = `<iframe src="${filePath}" width="100%" height="800px" style="border: none;"></iframe>`;
            } else if (['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {
                previewContainer.innerHTML = `<img src="${filePath}" class="img-fluid" style="max-height: 80vh;">`;
            } else {
                previewContainer.innerHTML = '<div class="text-white p-5">هذا النوع من الملفات غير مدعوم للمعاينة المباشرة</div>';
            }
            
            if (previewModal) previewModal.show();
        });
    });

    previewModalEl.addEventListener('hidden.bs.modal', function () {
        previewContainer.innerHTML = '';
    });

    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const form = this.closest('form');
            if (confirm('هل أنت متأكد من الحذف؟')) {
                form.submit();
            }
        });
    });
</script>

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