<?php
$canApprove = AdminMiddleware::can('product.approve');
$canHide    = AdminMiddleware::can('product.hide');

$statusMap = [
  'active'   => ['status-active', 'Active (วางขายปกติ)'],
  'pending'  => ['status-pending', 'รอการตรวจสอบ (Pending Review)'],
  'draft'    => ['status-secondary', 'ฉบับร่าง (Draft)'],
  'hidden'   => ['status-hidden', 'ซ่อนจากหน้าร้าน (Hidden)'],
  'rejected' => ['status-danger', 'ปฏิเสธ (Rejected)'],
];
[$pillClass, $pillLabel] = $statusMap[$product['status']] ?? ['status-secondary', $product['status']];
?>
<div class="mb-3">
  <a href="<?= url('/admin/products') ?>" 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"><?= e($product['name']) ?></h5>
        <span class="status-pill <?= $pillClass ?>"><?= $pillLabel ?></span>
      </div>
      <div class="text-muted small mt-1">
        ร้านค้า: <strong><?= e($product['store_name']) ?></strong> (@<?= e($product['seller_username']) ?>) &bull;
        หมวดหมู่: <strong><?= e($product['category_name'] ?? '—') ?></strong> &bull;
        Product ID: <span class="font-monospace">#<?= (int)$product['id'] ?></span>
      </div>
    </div>
  </div>

  <!-- Moderation Action Buttons Triggering Modals -->
  <div class="d-flex align-items-center gap-2 flex-wrap">
    <a href="<?= url('/product/' . (int)$product['id']) ?>" target="_blank" class="btn btn-outline-secondary btn-sm py-1 px-3">
      <i class="bi bi-box-arrow-up-right me-1"></i>พรีวิวสินค้า
    </a>

    <?php if ($product['status'] === 'pending' || $product['status'] === 'draft'): ?>
      <?php if ($canApprove): ?>
      <form action="<?= url('/admin/products/' . (int)$product['id'] . '/approve') ?>" method="POST" class="d-inline">
        <?= Security::csrfField() ?>
        <button type="submit" class="btn btn-success btn-sm py-1 px-3" onclick="return confirm('ยืนยันอนุมัติสินค้าชิ้นนี้ให้วางขายบน Marketplace?')">
          <i class="bi bi-check-circle me-1"></i>อนุมัติสินค้า (Approve)
        </button>
      </form>
      <button type="button" class="btn btn-outline-danger btn-sm py-1 px-3" data-bs-toggle="modal" data-bs-target="#rejectProductModal">
        <i class="bi bi-x-circle me-1"></i>ปฏิเสธสินค้า (Reject)
      </button>
      <?php endif; ?>

    <?php elseif ($product['status'] === 'active'): ?>
      <?php if ($canHide): ?>
      <button type="button" class="btn btn-outline-warning btn-sm py-1 px-3" data-bs-toggle="modal" data-bs-target="#hideProductModal">
        <i class="bi bi-eye-slash me-1"></i>ซ่อนสินค้า (Hide)
      </button>
      <?php endif; ?>

    <?php elseif ($product['status'] === 'hidden'): ?>
      <?php if ($canHide): ?>
      <form action="<?= url('/admin/products/' . (int)$product['id'] . '/restore') ?>" method="POST" class="d-inline">
        <?= Security::csrfField() ?>
        <button type="submit" class="btn btn-primary btn-sm py-1 px-3" onclick="return confirm('คืนสถานะให้สินค้ากลับมาวางขาย?')">
          <i class="bi bi-eye me-1"></i>คืนสถานะเป็น Active
        </button>
      </form>
      <?php endif; ?>

    <?php elseif ($product['status'] === 'rejected'): ?>
      <?php if ($canApprove): ?>
      <form action="<?= url('/admin/products/' . (int)$product['id'] . '/restore') ?>" method="POST" class="d-inline">
        <?= Security::csrfField() ?>
        <button type="submit" class="btn btn-outline-secondary btn-sm py-1 px-3" onclick="return confirm('ส่งสินค้ากลับไปยังสถานะรอตรวจสอบ?')">
          <i class="bi bi-arrow-counterclockwise me-1"></i>คืนสถานะเป็น รอตรวจสอบ
        </button>
      </form>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</div>

<div class="row g-4">
  <!-- Left Product Information & Gallery -->
  <div class="col-lg-8">
    <!-- Image Gallery Card -->
    <div class="admin-detail-card mb-4">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-images text-primary me-2"></i>รูปภาพสินค้า (Gallery)</span>
        <span class="badge bg-light text-muted border"><?= count($product['images'] ?? []) ?> รูป</span>
      </div>
      <div class="admin-detail-card-body p-3">
        <?php if (empty($product['images'])): ?>
          <div class="text-center text-muted py-3 small">ไม่มีรูปภาพประกอบสินค้า</div>
        <?php else: ?>
          <div class="d-flex gap-2 flex-wrap">
            <?php foreach ($product['images'] as $img): ?>
              <div class="rounded-3 border overflow-hidden position-relative bg-light flex-shrink-0" style="width: 100px; height: 100px;">
                <img src="<?= asset('/' . ltrim($img['image_path'], '/')) ?>" class="w-100 h-100 object-fit-cover" alt="">
                <?php if (!empty($img['is_main'])): ?>
                  <span class="badge bg-primary position-absolute bottom-0 start-0 m-1" style="font-size: 0.6rem;">หน้าปก</span>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Product Description -->
    <div class="admin-detail-card mb-4">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-file-text text-primary me-2"></i>รายละเอียดสินค้า (Description)</span>
      </div>
      <div class="admin-detail-card-body">
        <?php if (!empty($product['description'])): ?>
          <div class="small text-muted mb-0 lh-base" style="white-space: pre-wrap;"><?= e($product['description']) ?></div>
        <?php else: ?>
          <div class="text-muted small">ไม่มีรายละเอียดเพิ่มเติม</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- SKU Variation Matrix -->
    <?php if (!empty($product['skus'])): ?>
    <div class="admin-table-container">
      <div class="admin-table-header">
        <div class="d-flex align-items-center gap-2">
          <i class="bi bi-grid text-primary"></i>
          <span class="fw-bold text-dark" style="font-size: 0.9rem;">ตัวเลือกสินค้าและสต็อก (SKU Matrix)</span>
        </div>
      </div>
      <div class="table-responsive">
        <table class="admin-table">
          <thead>
            <tr>
              <th>ตัวเลือก / ขนาด / สี</th>
              <th>ราคาขาย</th>
              <th class="text-center">สต็อกคงเหลือ</th>
              <th>สถานะ SKU</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($product['skus'] as $sku): ?>
            <tr>
              <td class="fw-medium text-dark"><?= e($sku['variation_summary'] ?? 'Default SKU') ?></td>
              <td class="fw-semibold">฿<?= number_format((float)$sku['price'], 2) ?></td>
              <td class="text-center font-monospace small"><?= (int)$sku['stock'] ?></td>
              <td>
                <span class="badge bg-light text-muted border" style="font-size: 0.72rem;"><?= e($sku['status'] ?? 'available') ?></span>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <!-- Right Operational Column -->
  <div class="col-lg-4">
    <!-- Moderation Notes / Reason -->
    <?php if (!empty($product['moderation_note'])): ?>
    <div class="alert alert-danger border-danger small mb-4 rounded-3 shadow-xs">
      <div class="fw-bold mb-1"><i class="bi bi-exclamation-octagon me-1"></i>บันทึกการตรวจสอบล่าสุด:</div>
      <div><?= nl2br(e($product['moderation_note'])) ?></div>
    </div>
    <?php endif; ?>

    <!-- Product Summary Specs -->
    <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>ข้อมูลสเปกสินค้า</span>
      </div>
      <div class="admin-detail-card-body p-3">
        <dl class="row mb-0 small">
          <dt class="col-5 text-muted mb-2">ราคาตั้งต้น</dt>
          <dd class="col-7 fw-bold text-primary mb-2">฿<?= number_format((float)$product['price'], 2) ?></dd>

          <dt class="col-5 text-muted mb-2">สต็อกรวม</dt>
          <dd class="col-7 font-monospace mb-2"><?= (int)$product['stock'] ?> ชิ้น</dd>

          <dt class="col-5 text-muted mb-2">จังหวัดต้นทาง</dt>
          <dd class="col-7 mb-2"><?= e($product['province'] ?? '—') ?></dd>

          <dt class="col-5 text-muted mb-2">สร้างเมื่อ</dt>
          <dd class="col-7 mb-2"><?= date('d M Y H:i', strtotime($product['created_at'])) ?></dd>

          <dt class="col-5 text-muted mb-0">อัปเดตล่าสุด</dt>
          <dd class="col-7 mb-0"><?= date('d M Y H:i', strtotime($product['updated_at'])) ?></dd>
        </dl>
      </div>
    </div>

    <!-- Store & Vendor Info Card -->
    <div class="admin-detail-card">
      <div class="admin-detail-card-header">
        <span><i class="bi bi-shop text-primary me-2"></i>ผู้ขาย / ร้านค้า</span>
      </div>
      <div class="admin-detail-card-body p-3 small">
        <div class="fw-bold text-dark mb-1"><?= e($product['store_name']) ?></div>
        <div class="text-muted mb-2">เจ้าของ: <?= e($product['seller_username']) ?> (<?= e($product['seller_email']) ?>)</div>
        <div class="d-grid gap-1 mt-3">
          <a href="<?= url('/admin/sellers/' . (int)$product['store_id']) ?>" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-shop me-1"></i>ดูข้อมูลร้านค้านี้
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── Reject Product Modal ────────────────────────────── -->
<?php if ($canApprove): ?>
<div class="modal fade" id="rejectProductModal" tabindex="-1" aria-labelledby="rejectProductModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form action="<?= url('/admin/products/' . (int)$product['id'] . '/reject') ?>" method="POST">
        <?= Security::csrfField() ?>
        <div class="modal-header bg-danger text-white py-3">
          <h6 class="modal-title fw-bold" id="rejectProductModalLabel">
            <i class="bi bi-x-circle me-2"></i>ปฏิเสธสินค้า (Reject Listing)
          </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">
          <p class="mb-2 text-dark">
            สินค้า: <strong><?= e($product['name']) ?></strong> (ร้าน: <?= e($product['store_name']) ?>)
          </p>
          <div class="mb-3">
            <label class="form-label fw-semibold text-dark mb-1">เหตุผลในการปฏิเสธ <span class="text-danger">*</span></label>
            <textarea name="reason" class="form-control form-control-sm" rows="3" placeholder="ระบุเหตุผล เช่น ข้อมูลสินค้าไม่ถูกต้อง รูปภาพไม่ชัดเจน สินค้าผิดนโยบาย..." required></textarea>
            <div class="form-text">เหตุผลนี้จะถูกบันทึกและแสดงให้ผู้ขายทราบใน Seller Center เพื่อทำการแก้ไข</div>
          </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; ?>

<!-- ── Hide Product Modal ──────────────────────────────── -->
<?php if ($canHide): ?>
<div class="modal fade" id="hideProductModal" tabindex="-1" aria-labelledby="hideProductModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form action="<?= url('/admin/products/' . (int)$product['id'] . '/hide') ?>" method="POST">
        <?= Security::csrfField() ?>
        <div class="modal-header bg-warning text-dark py-3">
          <h6 class="modal-title fw-bold" id="hideProductModalLabel">
            <i class="bi bi-eye-slash me-2"></i>ซ่อนสินค้าจาก Marketplace (Hide)
          </h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body p-4 small">
          <p class="mb-2 text-dark">
            สินค้า: <strong><?= e($product['name']) ?></strong>
          </p>
          <div class="mb-3">
            <label class="form-label fw-semibold text-dark mb-1">เหตุผลในการซ่อน <span class="text-danger">*</span></label>
            <textarea name="reason" class="form-control form-control-sm" rows="3" placeholder="ระบุเหตุผลในการซ่อนสินค้า..." required></textarea>
            <div class="form-text">สินค้านี้จะไม่แสดงในหน้าค้นหาหรือหน้าร้านค้าของลูกค้าชั่วคราว</div>
          </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-warning px-3">
            <i class="bi bi-eye-slash me-1"></i>ยืนยันการซ่อนสินค้า
          </button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

