38808-vm/inbound.php
2026-02-28 05:28:11 +00:00

559 lines
26 KiB
PHP

<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/mail/MailService.php';
// Check if user has view permission
if (!canView('inbound')) {
redirect('index.php');
}
$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'] ?? '';
// Permission checks for POST actions
if (($action === 'add' && !canAdd('inbound')) || ($action === 'edit' && !canEdit('inbound'))) {
$error = 'عذراً، ليس لديك الصلاحية للقيام بهذا الإجراء';
} else {
$type = 'inbound';
$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);
}
$_SESSION['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 = 'inbound'");
$stmt->execute([$ref_no, $date_registered, $due_date, $sender, $recipient, $subject, $description, $status_id, $assigned_to, $id]);
if ($assigned_to && $assigned_to != $old_assigned_to) {
sendAssignmentNotification($assigned_to, $ref_no, $subject);
}
$_SESSION['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();
redirect('inbound.php');
} 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'])) {
if (!canDelete('inbound')) {
$error = 'عذراً، ليس لديك الصلاحية لحذف السجلات';
} else {
$id = $_GET['id'];
$stmt = db()->prepare("DELETE FROM mailbox WHERE id = ? AND type = 'inbound'");
$stmt->execute([$id]);
$_SESSION['success'] = 'تم حذف البريد بنجاح';
redirect('inbound.php');
}
}
// Get session messages
if (isset($_SESSION['success'])) {
$success = $_SESSION['success'];
unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
$error = $_SESSION['error'];
unset($_SESSION['error']);
}
$search = $_GET['search'] ?? '';
$my_tasks = isset($_GET['my_tasks']) && $_GET['my_tasks'] == 1;
// Pagination settings
$limit = 10; // Items per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;
$where_clauses = ["m.type = 'inbound'"];
$params = [];
if ($search) {
$where_clauses[] = "(m.ref_no LIKE ? OR m.sender LIKE ? OR m.subject LIKE ?)";
$params[] = "%$search%";
$params[] = "%$search%";
$params[] = "%$search%";
}
if ($my_tasks) {
$where_clauses[] = "m.assigned_to = ?";
$params[] = $user_id;
}
$where_sql = implode(" AND ", $where_clauses);
// Get total records for pagination
$count_query = "SELECT COUNT(*) FROM mailbox m WHERE $where_sql";
$stmt_count = db()->prepare($count_query);
$stmt_count->execute($params);
$total_records = $stmt_count->fetchColumn();
$total_pages = ceil($total_records / $limit);
// Fetch paginated results
$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 $where_sql
ORDER BY m.created_at DESC
LIMIT $limit OFFSET $offset";
$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'])) {
if (canEdit('inbound')) {
$stmt = db()->prepare("SELECT * FROM mailbox WHERE id = ? AND type = 'inbound'");
$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>
<?php if (canAdd('inbound')): ?>
<button type="button" class="btn btn-primary shadow-sm" onclick="openMailModal('add')">
<i class="fas fa-plus-circle me-1"></i> إضافة جديد
</button>
<?php endif; ?>
</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="inbound.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><?= htmlspecialchars($mail['subject']) ?></td>
<td><?= htmlspecialchars($mail['sender']) ?></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>
<?php if (canEdit('inbound')): ?>
<button type="button" class="btn btn-sm btn-outline-primary"
onclick='openMailModal("edit", <?= json_encode($mail) ?>)' title="تعديل">
<i class="fas fa-edit"></i>
</button>
<?php endif; ?>
<?php if (canDelete('inbound')): ?>
<a href="javascript:void(0)" onclick="confirmDelete(<?= $mail['id'] ?>)" class="btn btn-sm btn-outline-danger" title="حذف"><i class="fas fa-trash"></i></a>
<?php endif; ?>
</td>
</tr>
<?php endforeach; else: ?>
<tr>
<td colspan="8" class="text-center py-4 text-muted">لا يوجد بريد وارد مسجل حالياً</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<?php if ($total_pages > 1): ?>
<div class="card-footer bg-white border-0 py-3">
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center mb-0">
<li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
<a class="page-link" href="?page=<?= $page - 1 ?><?= $search ? '&search='.urlencode($search) : '' ?><?= $my_tasks ? '&my_tasks=1' : '' ?>" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<?php for ($i = 1; $i <= $total_pages; $i++): ?>
<li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
<a class="page-link" href="?page=<?= $i ?><?= $search ? '&search='.urlencode($search) : '' ?><?= $my_tasks ? '&my_tasks=1' : '' ?>"><?= $i ?></a>
</li>
<?php endfor; ?>
<li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
<a class="page-link" href="?page=<?= $page + 1 ?><?= $search ? '&search='.urlencode($search) : '' ?><?= $my_tasks ? '&my_tasks=1' : '' ?>" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
</div>
<?php endif; ?>
</div>
<?php if (canAdd('inbound') || canEdit('inbound')): ?>
<!-- Mail Modal -->
<div class="modal fade" id="mailModal" tabindex="-1" aria-labelledby="mailModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content border-0 shadow">
<div class="modal-header bg-primary 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 readonly>
</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="sender" id="modalSender" 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-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="modalDescription" class="form-control" rows="3"></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 mailModal;
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'),
description: document.getElementById('modalDescription'),
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 if (key === 'ref_no') fields[key].value = '<?= generateRefNo('inbound') ?>';
else fields[key].value = '';
}
});
} else {
label.textContent = 'تعديل البريد الوارد';
modalId.value = data.id;
Object.keys(fields).forEach(key => {
if (fields[key]) fields[key].value = data[key] || '';
});
}
mailModal.show();
}
document.addEventListener('DOMContentLoaded', function() {
<?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; ?>
});
function confirmDelete(id) {
if (typeof Swal === 'undefined') {
if (confirm('هل أنت متأكد من الحذف؟')) {
window.location.href = 'inbound.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 = 'inbound.php?action=delete&id=' + id;
}
})
}
</script>
<?php endif; ?>
<style>
.modal-content {
border-radius: 15px;
overflow: hidden;
}
.modal-header.bg-primary {
background-color: #0d6efd !important;
}
</style>
<?php require_once __DIR__ . '/includes/footer.php'; ?>