<?php
require_once __DIR__.'/../config/config.php';
require_user();
$U = current_user();
$id = (int)($_GET['id'] ?? 0);

// AJAX counter bump (copy)
if (isset($_GET['bump']) && $_GET['bump']==='copy') {
    $pdo->prepare("UPDATE orders SET copy_count=copy_count+1 WHERE id=? AND user_id=?")->execute([$id, $U['id']]);
    header('Content-Type: application/json'); echo json_encode(['ok'=>true]); exit;
}
// Download file
if (isset($_GET['dl'])) {
    $s = $pdo->prepare("SELECT * FROM orders WHERE id=? AND user_id=?");
    $s->execute([$id, $U['id']]); $o = $s->fetch();
    if (!$o || empty($o['delivery_file'])) die('Not found');
    $path = __DIR__.'/../uploads/deliveries/'.$o['delivery_file'];
    if (!file_exists($path)) die('File missing');
    $pdo->prepare("UPDATE orders SET download_count=download_count+1 WHERE id=?")->execute([$id]);
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($o['delivery_file']).'"');
    header('Content-Length: '.filesize($path));
    readfile($path); exit;
}

$s = $pdo->prepare("SELECT o.*, s.name AS sname FROM orders o LEFT JOIN services s ON s.id=o.service_id WHERE o.id=? AND o.user_id=?");
$s->execute([$id, $U['id']]);
$o = $s->fetch();
if (!$o) { die('Not found'); }

// mark notification seen
if (!empty($o['user_notified']) === false || $o['user_notified']==0) {
    $pdo->prepare("UPDATE orders SET user_notified=1 WHERE id=?")->execute([$id]);
}

$custom = $o['custom_data'] ? json_decode($o['custom_data'], true) : null;

$PAGE_TITLE = 'অর্ডার #'.$o['id'];
require __DIR__.'/_layout.php';
?>
<h2 style="margin-bottom:14px"><a href="history.php" style="text-decoration:none">←</a> অর্ডার #<?=$o['id']?></h2>

<div class="card">
  <p><b>সার্ভিস:</b> <?=e($o['sname'])?></p>
  <p><b>মূল্য:</b> <?=money($o['price'])?></p>
  <p><b>তারিখ:</b> <?=e($o['created_at'])?></p>
  <p><b>স্ট্যাটাস:</b>
    <?php $st=$o['status'];
      $map=['pending'=>['⏳ পেন্ডিং','#f59e0b'],'received'=>['📥 রিসিভ','#3b82f6'],'completed'=>['✅ সম্পাদন সম্পন্ন','#16a34a'],'success'=>['✅ সফল','#16a34a'],'cancelled'=>['❌ বাতিল','#dc2626'],'refund'=>['💸 রিফান্ড','#dc2626'],'failed'=>['❌ ব্যর্থ','#dc2626']];
      $m=$map[$st]??[e($st),'#64748b'];
    ?>
    <span style="background:<?=$m[1]?>;color:#fff;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:600"><?=$m[0]?></span>
  </p>

  <?php if($custom): ?>
    <?php if(($custom['type']??'')==='auto_nid'): ?>
      <hr><h4>🪪 অটো NID মেক — আপলোডকৃত ফাইল</h4>
      <?php $files = $custom['files'] ?? []; $labels=['pdf'=>'📄 Citizen PDF','photo'=>'🖼️ ছবি','sign'=>'✍️ সাক্ষর']; ?>
      <?php foreach($labels as $k=>$lbl): $rel=$files[$k]??null; if(!$rel) continue; ?>
        <div style="padding:6px 0;font-size:14px">
          <b><?=$lbl?>:</b>
          <a class="btn sm" href="../<?=e($rel)?>" target="_blank" rel="noopener">📥 ডাউনলোড</a>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <hr><h4>আপনার সাবমিটেড ডাটা</h4>
      <?php foreach($custom as $k=>$v): ?>
        <div style="padding:4px 0;font-size:14px"><b><?=e($k)?>:</b> <?=e(is_array($v)?json_encode($v,JSON_UNESCAPED_UNICODE):$v)?></div>
      <?php endforeach; ?>
    <?php endif; ?>
  <?php endif; ?>

  <?php if($st==='cancelled' && !empty($o['cancel_reason'])): ?>
    <hr>
    <div class="alert err"><b>❌ বাতিলের কারণ:</b><br><?=nl2br(e($o['cancel_reason']))?></div>
  <?php endif; ?>

  <?php if(in_array($st,['completed','success'],true)): ?>
    <hr><h4>📬 ডেলিভারি</h4>
    <?php if(in_array($o['delivery_type'],['text','link'],true) && !empty($o['delivery_content'])): ?>
      <div style="background:#f1f5f9;padding:12px;border-radius:10px;word-break:break-all;font-family:monospace;font-size:14px" id="deliveryContent"><?=nl2br(e($o['delivery_content']))?></div>
      <button class="btn" onclick="copyDelivery()" style="margin-top:10px">📋 কপি করুন</button>
      <?php if($o['delivery_type']==='link'): ?>
        <a class="btn ghost" href="<?=e($o['delivery_content'])?>" target="_blank" rel="noopener">🔗 ওপেন</a>
      <?php endif; ?>
    <?php endif; ?>

    <?php if(in_array($o['delivery_type'],['pdf','file'],true) && !empty($o['delivery_file'])): ?>
      <a class="btn" href="order_view.php?id=<?=$o['id']?>&dl=1">📥 ডাউনলোড করুন</a>
    <?php endif; ?>

    <p style="color:#94a3b8;font-size:12px;margin-top:12px">ডাউনলোড: <?=(int)$o['download_count']?> | কপি: <?=(int)$o['copy_count']?></p>
  <?php elseif($st==='pending' || $st==='received'): ?>
    <hr>
    <div class="alert info">⏳ আপনার অর্ডার প্রসেসিং-এ আছে। সম্পাদন হলে আপনাকে জানানো হবে।</div>
  <?php endif; ?>
</div>

<script>
async function copyDelivery(){
  const t = document.getElementById('deliveryContent').innerText;
  try{ await navigator.clipboard.writeText(t); alert('কপি হয়েছে!'); }
  catch(e){ alert('কপি ব্যর্থ'); }
  fetch('order_view.php?id=<?=$o['id']?>&bump=copy').catch(()=>{});
}
</script>
<?php require __DIR__.'/_footer.php';
