<?php
$typeLabel = [
  'product' => 'สินค้า (Product) #',
  'seller'  => 'ร้านค้า (Seller) #',
  'order'   => 'คำสั่งซื้อ (Order) #',
  'review'  => 'รีวิว (Review) #',
][$report['report_type']] ?? 'รายการ #';

$statusMap = [
  'pending'   => ['status-pending', 'รอดำเนินการ (Pending)'],
  'submitted' => ['status-pending', 'รอดำเนินการ (Pending)'],
  'reviewing' => ['status-preparing', 'กำลังตรวจสอบ (Reviewing)'],
  'resolved'  => ['status-active', 'แก้ไขแล้ว (Resolved)'],
  'rejected'  => ['status-danger', 'ปฏิเสธ (Rejected)'],
];
[$pillClass, $pillLabel] = $statusMap[$report['status']] ?? ['status-secondary', $report['status']];

$reporterFullName = trim(($report['reporter_first_name'] ?? '') . ' ' . ($report['reporter_last_name'] ?? ''));
if (empty($reporterFullName)) {
    $reporterFullName = $report['reporter_username'] ?? 'ผู้ใช้งาน';
}
?>
<div class="mb-3">
  <a href="<?= url('/admin/reports') ?>" class="btn btn-outline-secondary btn-sm py-1 px-3">
    <i class="bi bi-arrow-left me-1"></i>กลับรายการรายงานปัญหา
  </a>
</div>

<!-- ── Detail Summary Header ───────────────────────────── -->
<div class="admin-detail-summary-header">
  <div class="d-flex align-items-center gap-3">
    <div>
      <div class="d-flex align-items-center gap-2 flex-wrap">
        <h5 class="fw-bold mb-0 text-dark">รายงาน #<?= (int)$report['id'] ?> — <?= $typeLabel . (int)$report['target_id'] ?></h5>
        <span class="status-pill <?= $pillClass ?>"><?= $pillLabel ?></span>
      </div>
      <div class="text-muted small mt-1">
        ส่งโดย: <strong><?= e($reporterFullName) ?></strong> (@<?= e($report['reporter_username'] ?? '—') ?>) &bull;
        วันที่ส่ง: <?= date('d M Y • H:i', strtotime($report['created_at'])) ?>
      </div>
    </div>
  </div>

  <div class="d-flex align-items-center gap-2">
    <?php if ($report['report_type'] === 'product'): ?>
      <a href="<?= url('/admin/products/' . (int)$report['target_id']) ?>" target="_blank" class="btn btn-outline-primary btn-sm py-1 px-3">
        <i class="bi bi-box-seam me-1"></i>ตรวจสอบสินค้าที่ถูกรายงาน &rarr;
      </a>
    <?php elseif ($report['report_type'] === 'seller'): ?>
      <a href="<?= url('/admin/sellers/' . (int)$report['target_id']) ?>" target="_blank" class="btn btn-outline-primary btn-sm py-1 px-3">
        <i class="bi bi-shop me-1"></i>ตรวจสอบร้านค้าที่ถูกรายงาน &rarr;
      </a>
    <?php elseif ($report['report_type'] === 'order'): ?>
      <a href="<?= url('/admin/orders') ?>" target="_blank" class="btn btn-outline-primary btn-sm py-1 px-3">
        <i class="bi bi-receipt me-1"></i>ค้นหาคำสั่งซื้อที่เกี่ยวข้อง &rarr;
      </a>
    <?php elseif ($report['report_type'] === 'review'): ?>
      <a href="<?= url('/admin/reviews') ?>" target="_blank" class="btn btn-outline-primary btn-sm py-1 px-3">
        <i class="bi bi-star me-1"></i>ตรวจสอบรีวิวที่ถูกรายงาน &rarr;
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="row g-4">
  <!-- Left Report Content Column -->
  <div class="col-lg-8">
    <!-- Complaint Details Card -->
    <div class="admin-detail-card mb-4">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-file-earmark-text text-primary me-2"></i>รายละเอียดข้อร้องเรียน / รายงาน</span>
      </div>
      <div class="admin-detail-card-body">
        <div class="p-3 bg-light rounded-3 text-dark small lh-base mb-3">
          <?= nl2br(e($report['description'] ?? 'ไม่มีคำอธิบายเพิ่มเติมจากผู้รายงาน')) ?>
        </div>

        <!-- Evidence Images if provided -->
        <?php 
        $images = [];
        if (!empty($report['evidence_images'])) {
            $decoded = json_decode($report['evidence_images'], true);
            if (is_array($decoded)) {
                $images = $decoded;
            } else {
                $images = array_filter(array_map('trim', explode(',', $report['evidence_images'])));
            }
        }
        if (!empty($images)): 
        ?>
          <div class="mb-3">
            <h6 class="small fw-bold text-dark mb-2"><i class="bi bi-images me-1 text-primary"></i>หลักฐานประกอบรายงาน:</h6>
            <div class="d-flex flex-wrap gap-2">
              <?php foreach ($images as $img): ?>
                <a href="<?= e($img) ?>" target="_blank" class="d-inline-block border rounded-3 overflow-hidden" style="width: 100px; height: 100px;">
                  <img src="<?= e($img) ?>" class="w-100 h-100 object-fit-cover" alt="หลักฐาน">
                </a>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>

        <?php if (!empty($report['resolution_note'])): ?>
          <div class="alert alert-success border-success small mb-0 rounded-3">
            <div class="fw-bold mb-1">ผลการดำเนินการและข้อสรุป (Resolution Note):</div>
            <div><?= nl2br(e($report['resolution_note'])) ?></div>
            <?php if (!empty($report['assigned_admin_username'])): ?>
              <div class="text-muted small mt-2 border-top pt-1">
                ดำเนินการโดย: @<?= e($report['assigned_admin_username']) ?> &bull; เมื่อ <?= date('d/m/Y H:i', strtotime($report['updated_at'])) ?>
              </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Reported Target Entity Summary Card -->
    <?php if (!empty($report['target_info'])): ?>
      <div class="admin-detail-card mb-4">
        <div class="admin-detail-card-header">
          <span><i class="bi bi-info-circle text-primary me-2"></i>ข้อมูลเป้าหมายที่ถูกรายงาน (Target Summary)</span>
        </div>
        <div class="admin-detail-card-body small">
          <dl class="row mb-0">
            <?php if ($report['report_type'] === 'product'): ?>
              <dt class="col-4 text-muted mb-2">ชื่อสินค้า</dt>
              <dd class="col-8 mb-2 fw-semibold text-dark"><?= e($report['target_info']['name'] ?? '') ?></dd>
              <dt class="col-4 text-muted mb-2">ร้านค้าเจ้าของ</dt>
              <dd class="col-8 mb-2"><?= e($report['target_info']['store_name'] ?? '—') ?></dd>
              <dt class="col-4 text-muted mb-2">ราคา</dt>
              <dd class="col-8 mb-2 text-primary fw-bold">฿<?= number_format((float)($report['target_info']['price'] ?? 0), 2) ?></dd>
              <dt class="col-4 text-muted mb-0">สถานะสินค้า</dt>
              <dd class="col-8 mb-0"><span class="badge bg-light text-dark border"><?= e($report['target_info']['status'] ?? '') ?></span></dd>
            <?php elseif ($report['report_type'] === 'seller'): ?>
              <dt class="col-4 text-muted mb-2">ชื่อร้านค้า</dt>
              <dd class="col-8 mb-2 fw-semibold text-dark"><?= e($report['target_info']['store_name'] ?? '') ?></dd>
              <dt class="col-4 text-muted mb-2">เจ้าของร้าน</dt>
              <dd class="col-8 mb-2">@<?= e($report['target_info']['username'] ?? '—') ?></dd>
              <dt class="col-4 text-muted mb-0">สถานะร้านค้า</dt>
              <dd class="col-8 mb-0"><span class="badge bg-light text-dark border"><?= e($report['target_info']['status'] ?? '') ?></span></dd>
            <?php elseif ($report['report_type'] === 'order'): ?>
              <dt class="col-4 text-muted mb-2">เลขที่คำสั่งซื้อ</dt>
              <dd class="col-8 mb-2 font-monospace fw-bold text-dark"><?= e($report['target_info']['order_no'] ?? '') ?></dd>
              <dt class="col-4 text-muted mb-2">ยอดรวม</dt>
              <dd class="col-8 mb-2 text-primary fw-bold">฿<?= number_format((float)($report['target_info']['total_amount'] ?? 0), 2) ?></dd>
              <dt class="col-4 text-muted mb-0">สถานะคำสั่งซื้อ</dt>
              <dd class="col-8 mb-0"><span class="badge bg-light text-dark border"><?= e($report['target_info']['order_status'] ?? '') ?></span></dd>
            <?php elseif ($report['report_type'] === 'review'): ?>
              <dt class="col-4 text-muted mb-2">คะแนนรีวิว</dt>
              <dd class="col-8 mb-2 text-warning"><?= str_repeat('★', (int)($report['target_info']['rating'] ?? 0)) ?></dd>
              <dt class="col-4 text-muted mb-2">ผู้เขียนรีวิว</dt>
              <dd class="col-8 mb-2">@<?= e($report['target_info']['username'] ?? '—') ?></dd>
              <dt class="col-4 text-muted mb-0">ข้อความรีวิว</dt>
              <dd class="col-8 mb-0 text-muted"><?= e($report['target_info']['comment'] ?? '—') ?></dd>
            <?php endif; ?>
          </dl>
        </div>
      </div>
    <?php endif; ?>

    <!-- Reporter Profile Card -->
    <div class="admin-detail-card">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-person text-primary me-2"></i>ข้อมูลผู้รายงาน (Reporter)</span>
      </div>
      <div class="admin-detail-card-body small">
        <dl class="row mb-0">
          <dt class="col-4 text-muted mb-2">ชื่อผู้ใช้</dt>
          <dd class="col-8 mb-2"><?= e($reporterFullName) ?> (@<?= e($report['reporter_username'] ?? '—') ?>)</dd>
          <dt class="col-4 text-muted mb-2">อีเมลติดต่อ</dt>
          <dd class="col-8 mb-2"><?= e($report['reporter_email'] ?? '—') ?></dd>
          <dt class="col-4 text-muted mb-0">โปรไฟล์ผู้ใช้</dt>
          <dd class="col-8 mb-0">
            <a href="<?= url('/admin/users/' . (int)$report['reporter_id']) ?>" class="text-primary fw-medium">
              ดูประวัติผู้ใช้งาน &rarr;
            </a>
          </dd>
        </dl>
      </div>
    </div>
  </div>

  <!-- Right Moderation / Action Column -->
  <div class="col-lg-4">
    <div class="admin-detail-card">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-shield-check text-primary me-2"></i>ดำเนินการกับรายงาน (Actions)</span>
      </div>
      <div class="admin-detail-card-body p-3">
        <?php if ($report['status'] === 'pending'): ?>
          <form action="<?= url('/admin/reports/' . (int)$report['id'] . '/review') ?>" method="POST" class="mb-3">
            <?= Security::csrfField() ?>
            <button type="submit" class="btn btn-warning btn-sm w-100 py-2 fw-semibold">
              <i class="bi bi-eye me-1"></i>รับเรื่องและเริ่มตรวจสอบ (Review)
            </button>
          </form>
        <?php endif; ?>

        <?php if (in_array($report['status'], ['pending', 'reviewing'], true)): ?>
          <div class="d-grid gap-2">
            <button type="button" class="btn btn-success btn-sm py-2 fw-semibold" data-bs-toggle="modal" data-bs-target="#resolveReportModal">
              <i class="bi bi-check-circle me-1"></i>แก้ไขเสร็จสิ้น (Resolve)
            </button>
            <button type="button" class="btn btn-outline-danger btn-sm py-2" data-bs-toggle="modal" data-bs-target="#rejectReportModal">
              <i class="bi bi-x-circle me-1"></i>ปฏิเสธรายงาน (Reject)
            </button>
          </div>
        <?php else: ?>
          <div class="alert alert-light border text-muted small text-center mb-0">
            <i class="bi bi-check-circle text-success me-1"></i> รายงานนี้ได้รับการดำเนินการเรียบร้อยแล้ว
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- ── Resolve Report Modal ────────────────────────────── -->
<?php if (in_array($report['status'], ['pending', 'reviewing'], true)): ?>
<div class="modal fade" id="resolveReportModal" tabindex="-1" aria-labelledby="resolveReportModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form action="<?= url('/admin/reports/' . (int)$report['id'] . '/resolve') ?>" method="POST">
        <?= Security::csrfField() ?>
        <div class="modal-header bg-success text-white py-3">
          <h6 class="modal-title fw-bold" id="resolveReportModalLabel">
            <i class="bi bi-check-circle me-2"></i>ปิดรายงานปัญหา (Resolve Issue)
          </h6>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-4 small">
          <div class="mb-3">
            <label class="form-label fw-semibold text-dark mb-1">บันทึกผลการแก้ไข / มาตรการที่ดำเนินการ <span class="text-danger">*</span></label>
            <textarea name="resolution_note" class="form-control form-control-sm" rows="3" placeholder="ระบุการดำเนินการ เช่น ตักเตือนร้านค้า, ซ่อนสินค้าที่ผิดกฎ, ลบรีวิวที่ไม่เหมาะสม, ประสานงานคืนเงิน..." required></textarea>
          </div>
        </div>
        <div class="modal-footer py-2 bg-light">
          <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-sm btn-success px-3">
            <i class="bi bi-check-circle me-1"></i>ยืนยันปิดรายงาน
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ── Reject Report Modal ─────────────────────────────── -->
<div class="modal fade" id="rejectReportModal" tabindex="-1" aria-labelledby="rejectReportModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form action="<?= url('/admin/reports/' . (int)$report['id'] . '/reject') ?>" method="POST">
        <?= Security::csrfField() ?>
        <div class="modal-header bg-danger text-white py-3">
          <h6 class="modal-title fw-bold" id="rejectReportModalLabel">
            <i class="bi bi-x-circle me-2"></i>ปฏิเสธรายงานปัญหา (Dismiss Report)
          </h6>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-4 small">
          <div class="mb-3">
            <label class="form-label fw-semibold text-dark mb-1">เหตุผลในการปฏิเสธรายงาน</label>
            <textarea name="resolution_note" class="form-control form-control-sm" rows="3" placeholder="ระบุเหตุผล เช่น ข้อมูลหลักฐานไม่เพียงพอ ไม่พบความผิดปกติ ไม่ขัดต่อนโยบาย..."></textarea>
          </div>
        </div>
        <div class="modal-footer py-2 bg-light">
          <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-sm btn-danger px-3">
            <i class="bi bi-x-circle me-1"></i>ยืนยันปฏิเสธรายงาน
          </button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>
