<?php
// ============================================================
// modules/clerk/complaints.php — شكاوي أمين الضبط
// ============================================================
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/rbac.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/sidebar_helper.php';

requireLogin(); requireRole(ROLE_CLERK);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

$msg = $err = '';
$viewId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// ─── POST: تقديم شكوى جديدة ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $subject = trim($_POST['subject'] ?? '');
    $category = $_POST['category'] ?? '';
    $description = trim($_POST['description'] ?? '');
    $caseId = $_POST['related_case_id'] ?: null;
    if (!$subject || !$category || !$description) {
        $err = 'يرجى تعبئة جميع الحقول الإلزامية.';
    } else {
        $newId = createComplaint($user['id'], ROLE_CLERK, [
            'category' => $category, 'subject' => $subject, 'description' => $description,
            'related_case_id' => $caseId, 'priority' => $_POST['priority'] ?? 'normal',
        ]);
        $msg = 'تم تقديم شكواك بنجاح، سيتم إعلامك عند الرد عليها.';
        $viewId = $newId;
    }
}

// ─── POST: رد على شكوى قائمة ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'reply') {
    $cid = (int)($_POST['complaint_id'] ?? 0);
    $s = $pdo->prepare("SELECT id FROM complaints WHERE id=? AND user_id=?"); $s->execute([$cid, $user['id']]);
    if ($s->fetch() && trim($_POST['message'] ?? '') !== '') {
        addComplaintMessage($cid, $user['id'], ROLE_CLERK, trim($_POST['message']));
        $msg = 'تم إرسال ردك.';
        $viewId = $cid;
    }
}

$myCases = $pdo->prepare("SELECT id, case_number, title FROM cases WHERE clerk_id=? ORDER BY created_at DESC LIMIT 100");
$myCases->execute([$user['id']]);
$myCases = $myCases->fetchAll();

$stmt = $pdo->prepare("SELECT * FROM complaints WHERE user_id=? ORDER BY created_at DESC");
$stmt->execute([$user['id']]);
$complaints = $stmt->fetchAll();

$detail = null; $thread = [];
if ($viewId) {
    $s = $pdo->prepare("SELECT * FROM complaints WHERE id=? AND user_id=?");
    $s->execute([$viewId, $user['id']]);
    $detail = $s->fetch();
    if ($detail) {
        $t = $pdo->prepare("SELECT m.*, u.full_name FROM complaint_messages m JOIN users u ON u.id=m.sender_id WHERE m.complaint_id=? AND m.is_internal=0 ORDER BY m.created_at ASC");
        $t->execute([$viewId]);
        $thread = $t->fetchAll();
    }
}

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الشكاوي');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('complaints','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('الشكاوي', $notifCount); ?>
<div class="page-content">

<?php if ($msg): ?><div class="alert alert-success alert-dismissible mb-3"><i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($msg) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger alert-dismissible mb-3"><i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($err) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

<?php if ($detail): ?>
  <a href="complaints.php" class="btn btn-sm btn-outline-secondary mb-3"><i class="bi bi-arrow-right"></i> رجوع لكل شكاويي</a>
  <div class="panel mb-3">
    <div class="panel-header d-flex justify-content-between align-items-center">
      <div class="panel-title"><i class="bi bi-chat-square-text"></i> <?= htmlspecialchars($detail['subject']) ?></div>
      <span style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($detail['complaint_number']) ?></span>
    </div>
    <div class="panel-body">
      <p style="white-space:pre-wrap"><?= nl2br(htmlspecialchars($detail['description'])) ?></p>
      <div class="d-flex gap-2 flex-wrap">
        <?= complaintStatusBadge($detail['status']) ?>
        <?= complaintPriorityBadge($detail['priority']) ?>
        <span class="badge bg-secondary"><?= htmlspecialchars(COMPLAINT_CATEGORIES[$detail['category']] ?? $detail['category']) ?></span>
      </div>
      <?php if ($detail['resolution_note']): ?>
      <div class="alert alert-navy mt-3" style="font-size:13px"><strong>ملاحظة الإدارة:</strong> <?= htmlspecialchars($detail['resolution_note']) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="panel">
    <div class="panel-header"><div class="panel-title"><i class="bi bi-chat-dots"></i> المراسلات</div></div>
    <div class="panel-body">
      <?php if (empty($thread)): ?><p class="text-muted mb-0">لا توجد ردود بعد.</p><?php endif; ?>
      <?php foreach ($thread as $m): $mine = (int)$m['sender_id'] === (int)$user['id']; ?>
      <div class="mb-3 p-3" style="border-radius:12px;background:<?= $mine ? 'rgba(255,255,255,.04)' : 'rgba(201,168,76,.1)' ?>;border:1px solid rgba(255,255,255,.08)">
        <div class="d-flex justify-content-between mb-1"><strong style="font-size:13px"><?= $mine ? 'أنت' : htmlspecialchars($m['full_name']) ?></strong><small class="text-muted"><?= formatDate($m['created_at'], true) ?></small></div>
        <div style="font-size:13px;white-space:pre-wrap"><?= nl2br(htmlspecialchars($m['message'])) ?></div>
      </div>
      <?php endforeach; ?>
      <?php if (!in_array($detail['status'], ['closed'], true)): ?>
      <form method="POST" class="mt-3">
        <input type="hidden" name="action" value="reply">
        <input type="hidden" name="complaint_id" value="<?= $detail['id'] ?>">
        <textarea name="message" class="form-control mb-2" rows="3" placeholder="اكتب رسالتك..." required></textarea>
        <button type="submit" class="btn btn-gold btn-sm"><i class="bi bi-send"></i> إرسال</button>
      </form>
      <?php endif; ?>
    </div>
  </div>

<?php else: ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">شكاويي</h5>
    <button class="btn btn-gold" data-bs-toggle="modal" data-bs-target="#newComplaintModal"><i class="bi bi-plus-circle"></i> شكوى جديدة</button>
  </div>
  <div class="panel">
    <div class="table-responsive">
      <table class="table dt-table">
        <thead><tr><th>الرقم</th><th>الموضوع</th><th>الفئة</th><th>الأولوية</th><th>الحالة</th><th>التاريخ</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($complaints as $c): ?>
        <tr>
          <td><?= htmlspecialchars($c['complaint_number']) ?></td>
          <td><?= htmlspecialchars($c['subject']) ?></td>
          <td><?= htmlspecialchars(COMPLAINT_CATEGORIES[$c['category']] ?? $c['category']) ?></td>
          <td><?= complaintPriorityBadge($c['priority']) ?></td>
          <td><?= complaintStatusBadge($c['status']) ?></td>
          <td><?= formatDate($c['created_at']) ?></td>
          <td><a href="?id=<?= $c['id'] ?>" class="action-btn" title="عرض"><i class="bi bi-eye"></i></a></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($complaints)): ?><tr><td colspan="7" class="text-center text-muted py-4">لم تقدم أي شكوى بعد</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
<?php endif; ?>

</div></div>

<!-- New Complaint Modal -->
<div class="modal fade" id="newComplaintModal" tabindex="-1">
  <div class="modal-dialog modal-lg"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">تقديم شكوى جديدة</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <input type="hidden" name="action" value="create">
      <div class="modal-body">
        <label class="form-label">الفئة <span class="text-danger">*</span></label>
        <select name="category" class="form-select mb-3" required>
          <option value="">— اختر —</option>
          <?php foreach (COMPLAINT_CATEGORIES as $k=>$v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
        </select>
        <label class="form-label">قضية متعلقة (اختياري)</label>
        <select name="related_case_id" class="form-select mb-3">
          <option value="">— بدون —</option>
          <?php foreach ($myCases as $mc): ?><option value="<?= $mc['id'] ?>"><?= htmlspecialchars($mc['case_number'].' — '.$mc['title']) ?></option><?php endforeach; ?>
        </select>
        <label class="form-label">الأولوية</label>
        <select name="priority" class="form-select mb-3">
          <?php foreach (COMPLAINT_PRIORITY as $k=>$v): ?><option value="<?= $k ?>" <?= $k==='normal'?'selected':'' ?>><?= $v['label'] ?></option><?php endforeach; ?>
        </select>
        <label class="form-label">الموضوع <span class="text-danger">*</span></label>
        <input type="text" name="subject" class="form-control mb-3" required maxlength="255">
        <label class="form-label">الوصف التفصيلي <span class="text-danger">*</span></label>
        <textarea name="description" class="form-control" rows="5" required></textarea>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-gold"><i class="bi bi-send"></i> إرسال الشكوى</button></div>
    </form>
  </div></div>
</div>
<?php renderFoot(); ?>
