<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?php
$order = isset($order) && is_array($order) ? $order : [];
$details = isset($details) && is_array($details) ? $details : [];

if (!function_exists('sb_card_prop')) {
  function sb_card_prop($src, array $keys, $default = '')
  {
    foreach ($keys as $key) {
      if (is_object($src) && isset($src->$key) && $src->$key !== '' && $src->$key !== null) return $src->$key;
      if (is_array($src) && isset($src[$key]) && $src[$key] !== '' && $src[$key] !== null) return $src[$key];
    }
    return $default;
  }
}

if (!function_exists('sb_card_clean_text')) {
  function sb_card_clean_text($text, $default = '-')
  {
    if ($text === null) return $default;
    $text = html_entity_decode((string) $text, ENT_QUOTES, 'UTF-8');
    $text = preg_replace('/\s+/u', ' ', $text);
    $text = trim($text);
    return $text === '' ? $default : $text;
  }
}

if (!function_exists('sb_card_status_meta')) {
  function sb_card_status_meta($status)
  {
    $meta = job_status_meta((int)$status);
    return [$meta['label'], 'job-status', $meta['icon'], $meta['color']];
  }
}

if (!function_exists('sb_card_status_html')) {
  function sb_card_status_html($idDetail, $status, $cekBahan, $canManage)
  {
    list($label, $colorClass, $icon, $color) = sb_card_status_meta($status);
    if (!$canManage) {
      return '<span class="badge badge-' . $colorClass . '" style="background-color:' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8') . ';color:#fff">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</span>';
    }

    $encDetail = encrypt_url((int) $idDetail);
    return '<button class="btn btn-' . $colorClass . ' btn-icon-split btn-sm flat edit_baru" style="background-color:' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8') . ';border-color:' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8') . ';color:#fff"'
      . ' data-id="' . htmlspecialchars($encDetail, ENT_QUOTES, 'UTF-8') . '"'
      . ' data-status="' . (int) $status . '"'
      . ' data-cek-bahan="' . (int) $cekBahan . '">'
      . '<span class="icon text-white-50"><i class="fa fa-' . htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') . '"></i></span>'
      . '<span class="text">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</span>'
      . '</button>';
  }
}

if (!function_exists('sb_card_gallery_items')) {
  function sb_card_gallery_items($json)
  {
    $items = [];
    if (empty($json)) return $items;

    $decoded = @json_decode($json);
    if (!is_object($decoded) || empty($decoded->data) || !is_array($decoded->data)) {
      return $items;
    }

    foreach ($decoded->data as $item) {
      $title = trim((string) sb_card_prop($item, ['title', 'nama', 'name'], ''));
      $isi = trim((string) sb_card_prop($item, ['isi', 'value', 'val'], ''));
      $rawImage = trim((string) sb_card_prop($item, ['gambar', 'image', 'img'], ''));
      if ($rawImage === '') continue;

      $text = '';
      if ($title !== '' && $isi !== '') $text = $title . ': ' . $isi;
      elseif ($title !== '') $text = $title;
      elseif ($isi !== '') $text = $isi;

      $text = preg_replace('/^\s*:\s*/', '', $text);
      $text = trim(preg_replace('/\s+/', ' ', $text));
      $url = preg_match('#^https?://#i', $rawImage) ? $rawImage : base_url(ltrim($rawImage, '/'));

      if (!isset($items[$url])) {
        $items[$url] = [
          'url' => $url,
          'text' => $text !== '' ? $text : '-',
        ];
      }
    }

    return array_values($items);
  }
}

$level = isset($this->session->level) ? strtolower(trim((string) $this->session->level)) : '';
$idu = isset($this->session->idu) ? (int) $this->session->idu : 0;
$allowedLevels = ['admin', 'owner', 'operator', 'desain', 'kasir', 'keuangan'];
$canManageProgress = ($idu > 0 && $level !== '' && in_array($level, $allowedLevels, true));

$idInvoice = (int) ($order['id_invoice'] ?? 0);
$idTransaksi = (string) ($order['id_transaksi'] ?? '-');
$namaPelanggan = (string) ($order['nama_pelanggan'] ?? 'Umum');
$tglAmbil = (string) ($order['tgl_ambil'] ?? '');
$payLabel = (string) ($order['payment_label'] ?? 'Belum Lunas');
$payClass = (string) ($order['payment_class'] ?? 'belum');
?>

<style>
  .sb-card-preview{border:1px solid rgba(140,152,164,.28);border-radius:8px;background:#fff;box-shadow:0 2px 10px rgba(22,28,45,.08);overflow:hidden}
  .sb-card-preview .order-header{display:flex;gap:.75rem 1rem;align-items:center;justify-content:space-between;padding:.95rem 1rem;background:#f8fafc;border-bottom:1px solid rgba(140,152,164,.18)}
  .sb-card-preview .order-meta{display:flex;flex-wrap:wrap;gap:.5rem .75rem;align-items:center}
  .sb-card-preview .chip{display:inline-flex;align-items:center;gap:.45rem;padding:.3rem .55rem;border-radius:6px;font-size:.8rem;line-height:1.2;border:1px solid rgba(140,152,164,.28);background:#fff;color:#111827}
  .sb-card-preview .chip .dot{width:.5rem;height:.5rem;border-radius:999px;background:#4f46e5;box-shadow:0 0 0 2px rgba(79,70,229,.15) inset}
  .sb-card-preview .chip-order{background:#0f172a;color:#fff;border-color:#0f172a;font-weight:700}
  .sb-card-preview .chip-order .label{font-size:.75rem}
  .sb-card-preview .chip-order .order-code{font-size:1rem;font-weight:800}
  .sb-card-preview .chip-order .customer-name{font-weight:800}
  .sb-card-preview .chip-muted{background:#fff;color:#111827}
  .sb-card-preview .chip-pay{border-color:#fed7aa;background:#fff7ed;color:#9a3412}
  .sb-card-preview .chip-pay.lunas{border-color:#bbf7d0;background:#f0fdf4;color:#166534}
  .sb-card-preview .nested{padding:.75rem 1rem 1rem}
  .sb-card-preview .items-table{width:100%;border-collapse:separate;border-spacing:0;border:1px solid rgba(140,152,164,.28);border-radius:6px;overflow:hidden;background:#fff}
  .sb-card-preview .items-table th,.sb-card-preview .items-table td{padding:.75rem .8rem;border-top:1px solid rgba(140,152,164,.20);font-size:.86rem;color:#111827;vertical-align:middle}
  .sb-card-preview .items-table thead th{border-top:0;background:#f8fafc;font-weight:800;text-align:left;color:#020617}
  .sb-card-preview .items-table tbody tr:first-child td{border-top:1px solid rgba(140,152,164,.20)}
  .sb-card-preview .text-left{text-align:left}
  .sb-card-preview .btn-modernizer,.sb-card-preview .status-pillizer,.sb-card-preview .status-item-actions{width:100%;display:flex;align-items:center;justify-content:center}
  .sb-card-preview .btn,.sb-card-preview .badge,.sb-card-preview .btn-proof{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;min-width:146px;width:146px;height:38px;border-radius:6px;border:1px solid transparent;padding:.35rem .6rem;font-size:.85rem;font-weight:800;line-height:1.05;text-decoration:none;white-space:nowrap;cursor:pointer}
  .sb-card-preview .btn i,.sb-card-preview .btn-proof i{color:inherit;opacity:1}
  .sb-card-preview .btn-warning{background:#f59e0b;border-color:#d97706;color:#fff}
  .sb-card-preview .btn-proof{background:#fff;border-color:#cbd5e1;color:#0f172a;min-width:150px;width:auto}
  .sb-card-preview .btn-proof:hover,.sb-card-preview .btn:hover{transform:translateY(-1px);box-shadow:0 8px 22px rgba(22,28,45,.12);text-decoration:none}
  .sb-card-preview .fin-empty{color:#6b7280;font-size:.85rem}
  .sb-card-preview .status-cell,.sb-card-preview .progres-cell{text-align:center}
  .sb-card-preview .btn-sb-baru,.sb-card-preview .badge-sb-baru{background:#667085;border-color:#667085;color:#fff}
  .sb-card-preview .btn-sb-desain,.sb-card-preview .badge-sb-desain{background:linear-gradient(145deg,#b100ff 0%,#da27ff 100%);border-color:#b100ff;color:#fff}
  .sb-card-preview .btn-sb-cetak,.sb-card-preview .badge-sb-cetak{background:linear-gradient(145deg,#2869f2 0%,#2d8dff 100%);border-color:#2869f2;color:#fff}
  .sb-card-preview .btn-sb-selesai,.sb-card-preview .badge-sb-selesai{background:linear-gradient(145deg,#14a84c 0%,#1ccf60 100%);border-color:#14a84c;color:#fff}
  .sb-card-preview .btn-sb-diambil,.sb-card-preview .badge-sb-diambil{background:linear-gradient(145deg,#facc15 0%,#fde047 100%);border-color:#facc15;color:#111827}
  .sb-card-preview .btn-sb-dikirim,.sb-card-preview .badge-sb-dikirim{background:linear-gradient(145deg,#ec9b13 0%,#ffb22c 100%);border-color:#ec9b13;color:#111827}
  @media (max-width:768px){
    .sb-card-preview .order-header{flex-direction:column;align-items:flex-start}
    .sb-card-preview .items-table thead{display:none}
    .sb-card-preview .items-table,.sb-card-preview .items-table tbody,.sb-card-preview .items-table tr,.sb-card-preview .items-table td{display:block;width:100%}
    .sb-card-preview .items-table tr{border-top:1px solid rgba(140,152,164,.20);padding:.35rem .5rem}
    .sb-card-preview .items-table td{display:flex;justify-content:space-between;gap:1rem;border-top:1px dashed rgba(140,152,164,.20)}
    .sb-card-preview .items-table td:before{content:attr(data-label);font-weight:700;color:#475569}
    .sb-card-preview .status-pillizer,.sb-card-preview .btn-modernizer,.sb-card-preview .status-item-actions{justify-content:flex-end}
  }
</style>

<div class="sb-card-preview order-card" data-invoice="<?= $idInvoice; ?>">
  <div class="order-header">
    <div class="order-meta">
      <span class="chip chip-order">
        <span class="dot"></span>
        <span class="label">No. Order</span>:
        <span class="order-code"><?= htmlspecialchars($idTransaksi, ENT_QUOTES, 'UTF-8'); ?></span>
        <span class="sep">&bull;</span>
        <span class="customer-name"><?= htmlspecialchars($namaPelanggan, ENT_QUOTES, 'UTF-8'); ?></span>
      </span>
      <span class="chip chip-muted"><i class="fa fa-calendar-check-o"></i> <?= function_exists('dtimes') ? dtimes($tglAmbil) : htmlspecialchars($tglAmbil, ENT_QUOTES, 'UTF-8'); ?></span>
      <span class="chip chip-pay <?= htmlspecialchars($payClass, ENT_QUOTES, 'UTF-8'); ?>"><i class="fa fa-credit-card"></i> <?= htmlspecialchars($payLabel, ENT_QUOTES, 'UTF-8'); ?></span>
    </div>
  </div>

  <div class="nested">
    <?php if (empty($details)): ?>
      <div class="chip chip-muted">Detail item tidak tersedia.</div>
    <?php else: ?>
      <table class="items-table items-table-card" data-invoice="<?= $idInvoice; ?>">
        <thead>
          <tr>
            <th style="width:7%">QTY</th>
            <th style="width:15%">Produk</th>
            <th style="width:17%">Bahan</th>
            <th style="width:9%">Ukuran</th>
            <th style="width:10%">Keterangan</th>
            <th style="width:18%">Finishing</th>
            <th style="width:12%">Status</th>
            <th style="width:5%"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($details as $idx => $detail):
            $idDetail = (int) ($detail['id_rincianinvoice'] ?? 0);
            $status = (int) ($detail['status'] ?? 0);
            $galleryItems = sb_card_gallery_items($detail['detail'] ?? '');
            $catatanUrl = site_url('status-board/detail-catatan') . '?rid=' . $idDetail;
            $statusHtml = sb_card_status_html($idDetail, $status, (int) ($detail['cek_bahan'] ?? 0), $canManageProgress);
          ?>
            <tr data-st="<?= $status; ?>">
              <td data-label="QTY"><?= htmlspecialchars((string) ($detail['jumlah'] ?? 0), ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="text-left" data-label="Produk"><?= htmlspecialchars((string) ($detail['nama_produk'] ?? 'Produk'), ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="text-left" data-label="Bahan"><?= htmlspecialchars((string) ($detail['nama_bahan'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="text-left" data-label="Ukuran"><?= htmlspecialchars((string) ($detail['ukuran'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="text-left" data-label="Keterangan"><?= htmlspecialchars(sb_card_clean_text($detail['keterangan'] ?? '-', '-'), ENT_QUOTES, 'UTF-8'); ?></td>
              <td class="text-left" data-label="Finishing">
                <div class="btn-modernizer">
                  <button type="button" class="btn btn-warning btn-sm btn-catatan-popup" data-url="<?= htmlspecialchars($catatanUrl, ENT_QUOTES, 'UTF-8'); ?>" title="Isi Catatan">
                    <i class="fa fa-print"></i><span>Isi Catatan</span>
                  </button>
                </div>
              </td>
              <td class="text-left status-cell" data-label="Status">
                <span class="status-pillizer"><?= $statusHtml; ?></span>
              </td>
              <td class="text-left progres-cell" data-label="Progres">
                <?php if (!empty($galleryItems)): ?>
                  <div class="status-item-actions">
                    <button type="button"
                            class="btn-proof btn-catatan-gallery"
                            data-product="<?= htmlspecialchars((string) ($detail['nama_produk'] ?? 'Produk'), ENT_QUOTES, 'UTF-8'); ?>"
                            data-gallery="<?= htmlspecialchars(json_encode($galleryItems, JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8'); ?>">
                      <i class="fa fa-image"></i><span>Lihat Gambar (<?= count($galleryItems); ?>)</span>
                    </button>
                  </div>
                <?php else: ?>
                  <span class="fin-empty">-</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>
</div>
