38808-vm/outbound.php
2026-02-27 18:20:25 +00:00

521 lines
24 KiB
PHP

<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/mail/MailService.php';
// Safe truncation helper
if (!function_exists('truncate_text')) {
function truncate_text($text, $limit = 100) {
$text = strip_tags($text);
if (function_exists('mb_strimwidth')) {
return mb_strimwidth($text, 0, $limit, "...");
}
if (strlen($text) <= $limit) return $text;
return substr($text, 0, $limit) . "...";
}
}
$error = '';
$success = '';
$user_id = $_SESSION['user_id'];
// Fetch statuses
$statuses_list = db()->query("SELECT * FROM mailbox_statuses ORDER BY id ASC")->fetchAll();
$default_status_id = db()->query("SELECT id FROM mailbox_statuses WHERE is_default = 1 LIMIT 1")->fetchColumn() ?: 1;
// Function to send assignment notification
function sendAssignmentNotification($assigned_to_id, $ref_no, $subject) {
if (!$assigned_to_id) return;
$stmt = db()->prepare("SELECT full_name, email FROM users WHERE id = ?");
$stmt->execute([$assigned_to_id]);
$user = $stmt->fetch();
if ($user && !empty($user['email'])) {
$to = $user['email'];
$email_subject = "تنبيه: تم تعيين بريد جديد لك (رقم القيد: $ref_no)";
$htmlBody = "
<div dir='rtl' style='font-family: Arial, sans-serif;'>
<h2>مرحباً " . htmlspecialchars($user['full_name']) . "</h2>
<p>لقد تم تعيين مهمة بريد جديد لك في النظام.</p>
<table border='1' cellpadding='10' cellspacing='0' style='border-collapse: collapse;'>
<tr>
<th style='background-color: #f8f9fa;'>رقم القيد</th>
<td>" . htmlspecialchars($ref_no) . "</td>
</tr>
<tr>
<th style='background-color: #f8f9fa;'>الموضوع</th>
<td>" . htmlspecialchars($subject) . "</td>
</tr>
</table>
<p>يرجى الدخول للنظام لمتابعة المهمة.</p>
<br>
<p>هذا تنبيه تلقائي، يرجى عدم الرد.</p>
</div>
";
MailService::sendMail($to, $email_subject, $htmlBody);
}
}
// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
$type = 'outbound';
$ref_no = $_POST['ref_no'] ?? '';
$date_registered = $_POST['date_registered'] ?? date('Y-m-d');
$due_date = !empty($_POST['due_date']) ? $_POST['due_date'] : null;
$sender = $_POST['sender'] ?? '';
$recipient = $_POST['recipient'] ?? '';
$subject = $_POST['subject'] ?? '';
$description = $_POST['description'] ?? '';
$status_id = $_POST['status_id'] ?? $default_status_id;
$assigned_to = !empty($_POST['assigned_to']) ? $_POST['assigned_to'] : null;
$id = $_POST['id'] ?? 0;
if ($ref_no && $subject) {
try {
db()->beginTransaction();
if ($action === 'add') {
$stmt = db()->prepare("INSERT INTO mailbox (type, ref_no, date_registered, due_date, sender, recipient, subject, description, status_id, assigned_to, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$type, $ref_no, $date_registered, $due_date, $sender, $recipient, $subject, $description, $status_id, $assigned_to, $user_id]);
$mail_id = db()->lastInsertId();
if ($assigned_to) {
sendAssignmentNotification($assigned_to, $ref_no, $subject);
}
$success = 'تمت إضافة البريد الصادر بنجاح';
} elseif ($action === 'edit') {
$mail_id = $id;
// Get previous assigned_to to check if it changed
$stmt_old = db()->prepare("SELECT assigned_to FROM mailbox WHERE id = ?");
$stmt_old->execute([$id]);
$old_assigned_to = $stmt_old->fetchColumn();
$stmt = db()->prepare("UPDATE mailbox SET ref_no = ?, date_registered = ?, due_date = ?, sender = ?, recipient = ?, subject = ?, description = ?, status_id = ?, assigned_to = ? WHERE id = ? AND type = 'outbound'");
$stmt->execute([$ref_no, $date_registered, $due_date, $sender, $recipient, $subject, $description, $status_id, $assigned_to, $mail_id]);
if ($assigned_to && $assigned_to != $old_assigned_to) {
sendAssignmentNotification($assigned_to, $ref_no, $subject);
}
$success = 'تم تحديث البيانات بنجاح';
}
// Handle Attachments
if (!empty($_FILES['attachments']['name'][0])) {
$upload_dir = 'uploads/attachments/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
foreach ($_FILES['attachments']['name'] as $key => $name) {
if ($_FILES['attachments']['error'][$key] === 0) {
$file_name = time() . '_' . basename($name);
$target_path = $upload_dir . $file_name;
if (move_uploaded_file($_FILES['attachments']['tmp_name'][$key], $target_path)) {
$stmt = db()->prepare("INSERT INTO attachments (mail_id, display_name, file_path, file_name, file_size) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$mail_id, $name, $target_path, $name, $_FILES['attachments']['size'][$key]]);
}
}
}
}
db()->commit();
} catch (PDOException $e) {
db()->rollBack();
if ($e->getCode() == 23000) {
$error = 'رقم القيد مستخدم مسبقاً';
} else {
$error = 'حدث خطأ: ' . $e->getMessage();
}
}
} else {
$error = 'يرجى ملء الحقول المطلوبة (رقم القيد، الموضوع)';
}
}
// Delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = db()->prepare("DELETE FROM mailbox WHERE id = ? AND type = 'outbound'");
$stmt->execute([$id]);
$success = 'تم حذف البريد بنجاح';
}
$search = $_GET['search'] ?? '';
$my_tasks = isset($_GET['my_tasks']) && $_GET['my_tasks'] == 1;
$query = "SELECT m.*, s.name as status_name, s.color as status_color, u.full_name as assigned_to_name
FROM mailbox m
LEFT JOIN mailbox_statuses s ON m.status_id = s.id
LEFT JOIN users u ON m.assigned_to = u.id
WHERE m.type = 'outbound'";
$params = [];
if ($search) {
$query .= " AND (m.ref_no LIKE ? OR m.recipient LIKE ? OR m.subject LIKE ?)";
$params[] = "%$search%";
$params[] = "%$search%";
$params[] = "%$search%";
}
if ($my_tasks) {
$query .= " AND m.assigned_to = ?";
$params[] = $user_id;
}
$query .= " ORDER BY m.created_at DESC";
$stmt = db()->prepare($query);
$stmt->execute($params);
$mails = $stmt->fetchAll();
$users_list = db()->query("SELECT id, full_name FROM users ORDER BY full_name")->fetchAll();
// Handle Deep Link for Edit
$deepLinkData = null;
if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
$stmt = db()->prepare("SELECT * FROM mailbox WHERE id = ? AND type = 'outbound'");
$stmt->execute([$_GET['id']]);
$deepLinkData = $stmt->fetch();
}
function getStatusBadgeInList($mail) {
$status_name = $mail['status_name'] ?? 'غير معروف';
$status_color = $mail['status_color'] ?? '#6c757d';
// Translation for default statuses
$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>
<button type="button" class="btn btn-primary shadow-sm" onclick="openMailModal('add')">
<i class="fas fa-plus-circle me-1"></i> إضافة جديد
</button>
</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="card shadow-sm border-0 mb-4">
<div class="card-header bg-white py-3">
<form class="row g-3 align-items-center">
<div class="col-md-4">
<input type="text" name="search" class="form-control" placeholder="بحث برقم القيد أو الموضوع أو المستلم..." value="<?= htmlspecialchars($search) ?>">
</div>
<div class="col-md-3">
<div class="form-check form-switch mt-1">
<input class="form-check-input" type="checkbox" name="my_tasks" id="myTasksSwitch" value="1" <?= $my_tasks ? 'checked' : '' ?> onchange="this.form.submit()">
<label class="form-check-label fw-bold" for="myTasksSwitch">مهامي فقط</label>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-secondary px-4">بحث</button>
</div>
<?php if ($search || $my_tasks): ?>
<div class="col-auto">
<a href="outbound.php" class="btn btn-link text-decoration-none">إلغاء التصفية</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>المسؤول</th>
<th>الحالة</th>
<th class="pe-4 text-center">الإجراءات</th>
</tr>
</thead>
<tbody>
<?php if ($mails): foreach ($mails as $mail): ?>
<tr>
<td class="ps-4 fw-bold text-primary"><?= $mail['ref_no'] ?></td>
<td><?= $mail['date_registered'] ?></td>
<td>
<?php if ($mail['due_date']): ?>
<span class="<?= (strtotime($mail['due_date']) < time() && $mail['status_name'] != 'closed') ? 'text-danger fw-bold' : '' ?>">
<?= $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; ?>
</td>
<td><?= truncate_text($mail['subject'], 80) ?></td>
<td><?= htmlspecialchars($mail['recipient']) ?></td>
<td>
<?php if ($mail['assigned_to_name']): ?>
<span class="text-nowrap"><i class="fas fa-user-tag me-1 text-muted"></i> <?= htmlspecialchars($mail['assigned_to_name']) ?></span>
<?php else: ?>
<span class="text-muted">غير معين</span>
<?php endif; ?>
</td>
<td><?= getStatusBadgeInList($mail) ?></td>
<td class="pe-4 text-center">
<a href="view_mail.php?id=<?= $mail['id'] ?>" class="btn btn-sm btn-outline-info" title="عرض التفاصيل"><i class="fas fa-eye"></i></a>
<button type="button" class="btn btn-sm btn-outline-primary"
onclick='openMailModal("edit", <?= json_encode($mail) ?>)' title="تعديل">
<i class="fas fa-edit"></i>
</button>
<a href="javascript:void(0)" onclick="confirmDelete(<?= $mail['id'] ?>)" class="btn btn-sm btn-outline-danger" title="حذف"><i class="fas fa-trash"></i></a>
</td>
</tr>
<?php endforeach; else: ?>
<tr>
<td colspan="8" class="text-center py-4 text-muted">لا يوجد بريد صادر مسجل حالياً</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Mail Modal -->
<div class="modal fade" id="mailModal" tabindex="-1" aria-labelledby="mailModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content border-0 shadow">
<div class="modal-header bg-success text-white">
<h5 class="modal-title fw-bold" id="mailModalLabel">إضافة بريد صادر جديد</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="mailForm" method="POST" enctype="multipart/form-data">
<div class="modal-body p-4">
<input type="hidden" name="action" id="modalAction" value="add">
<input type="hidden" name="id" id="modalId" value="0">
<div class="row g-3">
<div class="col-md-4">
<label class="form-label fw-bold">رقم القيد <span class="text-danger">*</span></label>
<input type="text" name="ref_no" id="modalRefNo" class="form-control" required>
</div>
<div class="col-md-4">
<label class="form-label fw-bold">تاريخ التسجيل</label>
<input type="date" name="date_registered" id="modalDateRegistered" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label fw-bold">الموعد النهائي</label>
<input type="date" name="due_date" id="modalDueDate" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label fw-bold">المستلم الخارجي (الجهة المستلمة)</label>
<input type="text" name="recipient" id="modalRecipient" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label fw-bold">المرسل الداخلي (القسم/الموظف)</label>
<input type="text" name="sender" id="modalSender" class="form-control">
</div>
<div class="col-12">
<label class="form-label fw-bold">الموضوع <span class="text-danger">*</span></label>
<input type="text" name="subject" id="modalSubject" class="form-control" required>
</div>
<div class="col-12">
<label class="form-label fw-bold">الوصف / ملاحظات</label>
<textarea name="description" id="description_editor" class="form-control" rows="5"></textarea>
</div>
<div class="col-12">
<label class="form-label fw-bold">المرفقات</label>
<input type="file" name="attachments[]" class="form-control" multiple>
</div>
<div class="col-md-6">
<label class="form-label fw-bold">الحالة</label>
<select name="status_id" id="modalStatusId" class="form-select">
<?php foreach ($statuses_list as $s): ?>
<?php
$d_name = $s['name'];
if ($d_name == 'received') $d_name = 'تم الاستلام';
if ($d_name == 'in_progress') $d_name = 'قيد المعالجة';
if ($d_name == 'closed') $d_name = 'مكتمل / مغلق';
?>
<option value="<?= $s['id'] ?>"><?= htmlspecialchars($d_name) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6">
<label class="form-label fw-bold">الموظف المسؤول</label>
<select name="assigned_to" id="modalAssignedTo" class="form-select">
<option value="">-- اختر موظف --</option>
<?php foreach ($users_list as $u): ?>
<option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['full_name']) ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<div class="modal-footer bg-light">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
<button type="submit" class="btn btn-primary px-4">حفظ البيانات</button>
</div>
</form>
</div>
</div>
</div>
<script>
let descriptionEditor;
let mailModal;
function initEditors() {
if (typeof ClassicEditor === 'undefined') {
console.error('CKEditor not loaded');
return Promise.resolve();
}
const config = {
toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'undo', 'redo']
};
return ClassicEditor.create(document.querySelector('#description_editor'), config)
.then(editor => { descriptionEditor = editor; })
.catch(err => {
console.error('CKEditor Init Error:', err);
});
}
function openMailModal(action, data = null) {
if (!mailModal) {
const modalEl = document.getElementById('mailModal');
if (typeof bootstrap !== 'undefined') {
mailModal = new bootstrap.Modal(modalEl);
} else {
console.error('Bootstrap not loaded');
return;
}
}
const label = document.getElementById('mailModalLabel');
const modalAction = document.getElementById('modalAction');
const modalId = document.getElementById('modalId');
const fields = {
ref_no: document.getElementById('modalRefNo'),
date_registered: document.getElementById('modalDateRegistered'),
due_date: document.getElementById('modalDueDate'),
sender: document.getElementById('modalSender'),
recipient: document.getElementById('modalRecipient'),
subject: document.getElementById('modalSubject'),
status_id: document.getElementById('modalStatusId'),
assigned_to: document.getElementById('modalAssignedTo')
};
modalAction.value = action;
if (action === 'add') {
label.textContent = 'إضافة بريد صادر جديد';
modalId.value = '0';
Object.keys(fields).forEach(key => {
if (fields[key]) {
if (key === 'date_registered') fields[key].value = '<?= date('Y-m-d') ?>';
else if (key === 'status_id') fields[key].value = '<?= $default_status_id ?>';
else fields[key].value = '';
}
});
if (descriptionEditor) descriptionEditor.setData('');
else document.getElementById('description_editor').value = '';
} else {
label.textContent = 'تعديل البريد الصادر';
modalId.value = data.id;
Object.keys(fields).forEach(key => {
if (fields[key]) fields[key].value = data[key] || '';
});
if (descriptionEditor) descriptionEditor.setData(data.description || '');
else document.getElementById('description_editor').value = data.description || '';
}
mailModal.show();
}
document.addEventListener('DOMContentLoaded', function() {
initEditors().finally(() => {
<?php if ($deepLinkData): ?>
openMailModal('edit', <?= json_encode($deepLinkData) ?>);
<?php elseif ($error && isset($_POST['action'])): ?>
const errorData = <?= json_encode([
'id' => $_POST['id'] ?? 0,
'ref_no' => $_POST['ref_no'] ?? '',
'date_registered' => $_POST['date_registered'] ?? date('Y-m-d'),
'due_date' => $_POST['due_date'] ?? '',
'sender' => $_POST['sender'] ?? '',
'recipient' => $_POST['recipient'] ?? '',
'subject' => $_POST['subject'] ?? '',
'description' => $_POST['description'] ?? '',
'status_id' => $_POST['status_id'] ?? $default_status_id,
'assigned_to' => $_POST['assigned_to'] ?? ''
]) ?>;
openMailModal('<?= $_POST['action'] ?>', errorData);
<?php elseif (isset($_GET['action']) && $_GET['action'] === 'add'): ?>
openMailModal('add');
<?php endif; ?>
});
document.getElementById('mailForm').addEventListener('submit', function() {
if (descriptionEditor) descriptionEditor.updateSourceElement();
});
});
function confirmDelete(id) {
if (typeof Swal === 'undefined') {
if (confirm('هل أنت متأكد من الحذف؟')) {
window.location.href = 'outbound.php?action=delete&id=' + id;
}
return;
}
Swal.fire({
title: 'هل أنت متأكد؟',
text: "لا يمكن التراجع عن عملية الحذف!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: 'نعم، احذف!',
cancelButtonText: 'إلغاء'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = 'outbound.php?action=delete&id=' + id;
}
})
}
</script>
<style>
.ck-editor__editable_inline {
min-height: 250px;
}
.modal-content {
border-radius: 15px;
overflow: hidden;
}
.modal-header.bg-success {
background-color: #198754 !important;
}
</style>
<?php require_once __DIR__ . '/includes/footer.php'; ?>