38808-vm/outbound.php
2026-02-27 15:17:13 +00:00

361 lines
17 KiB
PHP

<?php
require_once __DIR__ . '/includes/header.php';
$error = '';
$success = '';
// 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');
$sender = $_POST['sender'] ?? '';
$recipient = $_POST['recipient'] ?? '';
$subject = $_POST['subject'] ?? '';
$description = $_POST['description'] ?? '';
$status = $_POST['status'] ?? 'received';
$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, sender, recipient, subject, description, status, assigned_to, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$type, $ref_no, $date_registered, $sender, $recipient, $subject, $description, $status, $assigned_to, $_SESSION['user_id']]);
$mail_id = db()->lastInsertId();
$success = 'تمت إضافة البريد الصادر بنجاح';
} elseif ($action === 'edit') {
$mail_id = $id;
$stmt = db()->prepare("UPDATE mailbox SET ref_no = ?, date_registered = ?, sender = ?, recipient = ?, subject = ?, description = ?, status = ?, assigned_to = ? WHERE id = ? AND type = 'outbound'");
$stmt->execute([$ref_no, $date_registered, $sender, $recipient, $subject, $description, $status, $assigned_to, $mail_id]);
$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, file_path, file_name, file_size) VALUES (?, ?, ?, ?)");
$stmt->execute([$mail_id, $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'] ?? '';
$query = "SELECT * FROM mailbox WHERE type = 'outbound'";
$params = [];
if ($search) {
$query .= " AND (ref_no LIKE ? OR recipient LIKE ? OR subject LIKE ?)";
$params = ["%$search%", "%$search%", "%$search%"];
}
$query .= " ORDER BY 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();
}
?>
<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" 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-2">
<div class="col-md-4">
<input type="text" name="search" class="form-control" placeholder="بحث برقم القيد أو الموضوع أو المستلم..." value="<?= htmlspecialchars($search) ?>">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-secondary">بحث</button>
</div>
</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="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><?= mb_strimwidth(strip_tags($mail['subject']), 0, 100, "...") ?></td>
<td><?= htmlspecialchars($mail['recipient']) ?></td>
<td>
<?php if ($mail['status'] === 'received'): ?>
<span class="badge bg-secondary">تم الاستلام</span>
<?php elseif ($mail['status'] === 'in_progress'): ?>
<span class="badge bg-info text-dark">قيد المعالجة</span>
<?php elseif ($mail['status'] === 'closed'): ?>
<span class="badge bg-success">مكتمل</span>
<?php endif; ?>
</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="6" 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">
<div class="modal-header">
<h5 class="modal-title" id="mailModalLabel">إضافة بريد صادر جديد</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="mailForm" method="POST" enctype="multipart/form-data">
<div class="modal-body">
<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-6">
<label class="form-label">رقم القيد <span class="text-danger">*</span></label>
<input type="text" name="ref_no" id="modalRefNo" class="form-control" required>
</div>
<div class="col-md-6">
<label class="form-label">تاريخ التسجيل</label>
<input type="date" name="date_registered" id="modalDateRegistered" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label">المستلم الخارجي (الجهة المستلمة)</label>
<input type="text" name="recipient" id="modalRecipient" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label">المرسل الداخلي (القسم/الموظف)</label>
<input type="text" name="sender" id="modalSender" class="form-control">
</div>
<div class="col-12">
<label class="form-label">الموضوع <span class="text-danger">*</span></label>
<textarea name="subject" id="subject_editor" class="form-control" rows="2"></textarea>
</div>
<div class="col-12">
<label class="form-label">الوصف / ملاحظات</label>
<textarea name="description" id="description_editor" class="form-control" rows="5"></textarea>
</div>
<div class="col-12">
<label class="form-label">المرفقات</label>
<input type="file" name="attachments[]" class="form-control" multiple>
<div class="form-text text-muted">يمكنك اختيار ملفات متعددة.</div>
</div>
<div class="col-md-6">
<label class="form-label">الحالة</label>
<select name="status" id="modalStatus" class="form-select">
<option value="received">تم الاستلام</option>
<option value="in_progress">قيد المعالجة</option>
<option value="closed">مكتمل / مغلق</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">الموظف المسؤول</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">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
<button type="submit" class="btn btn-primary">حفظ البيانات</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.ckeditor.com/ckeditor5/36.0.1/classic/ckeditor.js"></script>
<script>
let subjectEditor, descriptionEditor;
function initEditors() {
return Promise.all([
ClassicEditor.create(document.querySelector('#subject_editor'), {
language: { content: 'ar', ui: 'ar' },
toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'undo', 'redo']
}).then(editor => { subjectEditor = editor; }),
ClassicEditor.create(document.querySelector('#description_editor'), {
language: { content: 'ar', ui: 'ar' },
toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', '|', 'undo', 'redo']
}).then(editor => { descriptionEditor = editor; })
]);
}
const mailModalElement = document.getElementById('mailModal');
const mailModal = new bootstrap.Modal(mailModalElement);
function openMailModal(action, data = null) {
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'),
sender: document.getElementById('modalSender'),
recipient: document.getElementById('modalRecipient'),
status: document.getElementById('modalStatus'),
assigned_to: document.getElementById('modalAssignedTo')
};
modalAction.value = action;
if (action === 'add') {
label.textContent = 'إضافة بريد صادر جديد';
modalId.value = '0';
Object.keys(fields).forEach(key => {
if (key === 'date_registered') fields[key].value = '<?= date('Y-m-d') ?>';
else if (key === 'status') fields[key].value = 'received';
else fields[key].value = '';
});
if (subjectEditor) subjectEditor.setData('');
if (descriptionEditor) descriptionEditor.setData('');
} else {
label.textContent = 'تعديل البريد الصادر';
modalId.value = data.id;
Object.keys(fields).forEach(key => {
fields[key].value = data[key] || '';
});
if (subjectEditor) subjectEditor.setData(data.subject || '');
if (descriptionEditor) descriptionEditor.setData(data.description || '');
}
mailModal.show();
}
document.addEventListener('DOMContentLoaded', function() {
initEditors().then(() => {
// Deep link or error handling
<?php if ($deepLinkData): ?>
openMailModal('edit', <?= json_encode($deepLinkData) ?>);
<?php elseif ($error && isset($_POST['action'])): ?>
const data = {
id: '<?= $_POST['id'] ?? 0 ?>',
ref_no: '<?= addslashes($_POST['ref_no'] ?? '') ?>',
date_registered: '<?= $_POST['date_registered'] ?? date('Y-m-d') ?>',
sender: '<?= addslashes($_POST['sender'] ?? '') ?>',
recipient: '<?= addslashes($_POST['recipient'] ?? '') ?>',
subject: `<?= addslashes($_POST['subject'] ?? '') ?>`,
description: `<?= addslashes($_POST['description'] ?? '') ?>`,
status: '<?= $_POST['status'] ?? 'received' ?>',
assigned_to: '<?= $_POST['assigned_to'] ?? '' ?>'
};
openMailModal('<?= $_POST['action'] ?>', data);
<?php elseif (isset($_GET['action']) && $_GET['action'] === 'add'): ?>
openMailModal('add');
<?php endif; ?>
});
});
function confirmDelete(id) {
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: 100px;
}
#description_editor + .ck-editor .ck-editor__editable_inline {
min-height: 250px;
}
</style>
<?php require_once __DIR__ . '/includes/footer.php'; ?>