<?php
// ============================================================
// modules/admin/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_ADMIN);
$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'] ?? '') === 'reply') {
    $cid = (int)($_POST['complaint_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    $isInternal = !empty($_POST['is_internal']);
    if ($cid && $message !== '') {
        addComplaintMessage($cid, $user['id'], ROLE_ADMIN, $message, $isInternal);
        // أي رد فعلي (غير ملاحظة داخلية) على شكوى "جديدة" ينقلها تلقائياً لقيد المعالجة
        if (!$isInternal) {
            $pdo->prepare("UPDATE complaints SET status = IF(status='new','in_review',status) WHERE id=?")->execute([$cid]);
        }
        $msg = 'تم إرسال الرد بنجاح.';
        $viewId = $cid;
    }
}

// ─── POST: تحديث الحالة / الإسناد ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_status') {
    $cid = (int)($_POST['complaint_id'] ?? 0);
    $status = $_POST['status'] ?? '';
    $assignedTo = $_POST['assigned_to'] ?: null;
    $note = trim($_POST['resolution_note'] ?? '');
    if ($cid && array_key_exists($status, COMPLAINT_STATUS)) {
        $resolvedAt = in_array($status, ['resolved','rejected','closed'], true) ? date('Y-m-d H:i:s') : null;
        $pdo->prepare("UPDATE complaints SET status=?, assigned_to=?, resolution_note=?, resolved_at=? WHERE id=?")
            ->execute([$status, $assignedTo, $note ?: null, $resolvedAt, $cid]);

        $c = $pdo->prepare("SELECT * FROM complaints WHERE id=?"); $c->execute([$cid]); $complaint = $c->fetch();
        if ($complaint) {
            createNotification((int)$complaint['user_id'], 'complaint_status', 'تحديث حالة شكواك',
                'تم تحديث حالة الشكوى ' . $complaint['complaint_number'] . ' إلى: ' . (COMPLAINT_STATUS[$status]['label'] ?? $status),
                BASE_URL . '/modules/' . $complaint['user_role'] . '/complaints.php?id=' . $cid);
        }
        auditLog($user['id'], 'update_complaint_status', 'complaints', $cid, 'تغيير الحالة إلى ' . $status);
        $msg = 'تم تحديث حالة الشكوى.';
        $viewId = $cid;
    }
}

// ─── فلاتر القائمة ───────────────────────────────────────────
$fStatus = $_GET['status'] ?? '';
$fCategory = $_GET['category'] ?? '';
$where = []; $params = [];
if ($fStatus)   { $where[] = 'c.status = ?';   $params[] = $fStatus; }
if ($fCategory) { $where[] = 'c.category = ?'; $params[] = $fCategory; }
$whereSQL = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$stmt = $pdo->prepare("SELECT c.*, u.full_name, u.email FROM complaints c JOIN users u ON u.id=c.user_id $whereSQL ORDER BY c.created_at DESC");
$stmt->execute($params);
$complaints = $stmt->fetchAll();

// ─── تفاصيل شكوى محددة ──────────────────────────────────────
$detail = null; $thread = []; $admins = [];
if ($viewId) {
    $s = $pdo->prepare("SELECT c.*, u.full_name, u.email, u.phone FROM complaints c JOIN users u ON u.id=c.user_id WHERE c.id=?");
    $s->execute([$viewId]);
    $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=? ORDER BY m.created_at ASC");
        $t->execute([$viewId]);
        $thread = $t->fetchAll();
        $admins = $pdo->query("SELECT id, full_name FROM users WHERE role='admin' AND status='active'")->fetchAll();
    }
}

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الشكاوي');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('complaints','admin'); ?></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 ($detail): ?>
  <!-- ================= تفاصيل الشكوى ================= -->
  <a href="complaints.php" class="btn btn-sm btn-outline-secondary mb-3"><i class="bi bi-arrow-right"></i> رجوع لكل الشكاوي</a>
  <div class="row g-3">
    <div class="col-lg-8">
      <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>
            <?php if ($detail['related_case_id']): ?><span class="badge bg-dark">قضية #<?= (int)$detail['related_case_id'] ?></span><?php endif; ?>
          </div>
        </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 = $m['sender_role'] === 'admin';
          ?>
          <div class="mb-3 p-3" style="border-radius:12px;background:<?= $m['is_internal'] ? 'rgba(181,38,38,.06)' : ($mine ? 'var(--gold-pale)' : 'var(--cream)') ?>;border:1px solid var(--border)">
            <div class="d-flex justify-content-between mb-1">
              <strong style="font-size:13px"><?= htmlspecialchars($m['full_name']) ?> <?= $m['is_internal'] ? '<span class="badge bg-danger">ملاحظة داخلية</span>' : '' ?></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; ?>

          <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>
            <div class="d-flex justify-content-between align-items-center">
              <div class="form-check">
                <input type="checkbox" class="form-check-input" name="is_internal" id="isInternal" value="1">
                <label class="form-check-label" for="isInternal" style="font-size:12px">ملاحظة داخلية (لا يراها صاحب الشكوى)</label>
              </div>
              <button type="submit" class="btn btn-gold btn-sm"><i class="bi bi-send"></i> إرسال</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="panel mb-3">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-person"></i> صاحب الشكوى</div></div>
        <div class="panel-body" style="font-size:13px">
          <div><strong><?= htmlspecialchars($detail['full_name']) ?></strong></div>
          <div class="text-muted"><?= htmlspecialchars($detail['email']) ?></div>
          <div class="text-muted"><?= htmlspecialchars($detail['phone'] ?? '—') ?></div>
          <div class="mt-2"><span class="badge bg-navy"><?= ['admin'=>'مدير','clerk'=>'أمين ضبط','lawyer'=>'محامي'][$detail['user_role']] ?? $detail['user_role'] ?></span></div>
        </div>
      </div>

      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-gear"></i> إدارة الشكوى</div></div>
        <div class="panel-body">
          <form method="POST">
            <input type="hidden" name="action" value="update_status">
            <input type="hidden" name="complaint_id" value="<?= $detail['id'] ?>">
            <label class="form-label" style="font-size:12px">الحالة</label>
            <select name="status" class="form-select mb-2">
              <?php foreach (COMPLAINT_STATUS as $k=>$v): ?>
              <option value="<?= $k ?>" <?= $detail['status']===$k?'selected':'' ?>><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
            <label class="form-label" style="font-size:12px">إسناد إلى</label>
            <select name="assigned_to" class="form-select mb-2">
              <option value="">— بدون إسناد —</option>
              <?php foreach ($admins as $a): ?>
              <option value="<?= $a['id'] ?>" <?= (int)$detail['assigned_to']===(int)$a['id']?'selected':'' ?>><?= htmlspecialchars($a['full_name']) ?></option>
              <?php endforeach; ?>
            </select>
            <label class="form-label" style="font-size:12px">ملاحظة الحل (اختياري)</label>
            <textarea name="resolution_note" class="form-control mb-2" rows="2"><?= htmlspecialchars($detail['resolution_note'] ?? '') ?></textarea>
            <button type="submit" class="btn btn-navy w-100"><i class="bi bi-check2-circle"></i> حفظ التحديث</button>
          </form>
        </div>
      </div>
    </div>
  </div>

<?php else: ?>
  <!-- ================= قائمة الشكاوي ================= -->
  <div class="d-flex gap-2 mb-3 flex-wrap">
    <?php foreach ([''=>'الكل'] + array_map(fn($v)=>$v['label'], COMPLAINT_STATUS) as $k=>$label):
      $active = ($fStatus===$k) ? 'btn-navy' : 'btn-outline-secondary';
    ?>
    <a href="?status=<?= $k ?>" class="btn btn-sm <?= $active ?>"><?= $label ?></a>
    <?php endforeach; ?>
  </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><th></th></tr></thead>
        <tbody>
        <?php foreach ($complaints as $c): ?>
        <tr>
          <td><?= htmlspecialchars($c['complaint_number']) ?></td>
          <td><strong><?= htmlspecialchars($c['full_name']) ?></strong><div style="font-size:11px;color:var(--text-muted)"><?= ['admin'=>'مدير','clerk'=>'أمين ضبط','lawyer'=>'محامي'][$c['user_role']] ?? '' ?></div></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; ?>
        </tbody>
      </table>
    </div>
  </div>
<?php endif; ?>

</div></div>
<?php renderFoot(); ?>
