<?php
require_once __DIR__.'/../inc/config.php';
require_once __DIR__.'/../inc/db.php';
require_once __DIR__.'/../inc/csrf.php';
require_once __DIR__.'/../inc/helpers.php';
require_once __DIR__.'/../inc/http.php';

if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; }

if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!csrf_verify()) die('CSRF');
  
  $id = (int)$_POST['id'];
  $status = $_POST['status'] ?? 'Pending';
  $tracking = trim($_POST['tracking_no'] ?? '');

  $st_old = db()->prepare("SELECT * FROM orders WHERE id=?");
  $st_old->execute([$id]);
  $old_order = $st_old->fetch();

  $st_update = db()->prepare("UPDATE orders SET status=?, tracking_no=? WHERE id=?");
  $st_update->execute([$status, $tracking, $id]);

  if (
      setting('WHATSAPP_NOTIF_TRACKING_ENABLED') == '1' && 
      !empty($tracking) && 
      $old_order && $tracking !== $old_order['tracking_no']
  ) {
      $tracking_template = setting('WHATSAPP_NOTIF_TRACKING_TEMPLATE', "Hai {nama}, pesanan #{id_pesanan} anda telah dihantar. No tracking: {no_tracking}");
      $tracking_message = str_replace(
          ['{nama}', '{id_pesanan}', '{no_tracking}'],
          [$old_order['name'], $old_order['id'], $tracking],
          $tracking_template
      );
      send_whatsapp($old_order['phone'], $tracking_message);
  }
  
  header('Location: orders.php?page='.($_GET['page']??1));
  exit;
}

$page=max(1,(int)($_GET['page']??1)); $per=20; $off=($page-1)*$per;
$total=(int)db()->query("SELECT COUNT(*) c FROM orders")->fetch()['c']; $pages=max(1,(int)ceil($total/$per));
$st=db()->prepare("SELECT o.*, pk.description as package_description, (SELECT p.file_path FROM payment_proofs p WHERE p.order_id = o.id ORDER BY p.id DESC LIMIT 1) as proof_file_path FROM orders o LEFT JOIN packages pk ON o.package_id = pk.id ORDER BY o.id DESC LIMIT ? OFFSET ?");
$st->bindValue(1,$per,PDO::PARAM_INT); $st->bindValue(2,$off,PDO::PARAM_INT); $st->execute(); $rows=$st->fetchAll();
?>
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../public/assets/css/style.css"><title>Orders</title>
<style>
    .admin-wrapper { display: flex; align-items: flex-start; gap: 24px; }
    .admin-sidebar { width: 220px; flex-shrink: 0; }
    .admin-content { flex-grow: 1; }
    table { width: 100%; border-collapse: collapse; font-size: 14px; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; vertical-align: middle; }
    th { background-color: #f8fafc; }
    .action-form { display: flex; gap: 6px; align-items: center; }
    .action-form select, .action-form input { padding: 6px; border-radius: 6px; border: 1px solid #ccc; }
    .action-form button { font-size: 12px; padding: 6px 10px; }
    .proof-thumbnail { width: 60px; height: 60px; object-fit: cover; border-radius: 6px; border: 1px solid #ddd; cursor: pointer; transition: transform 0.2s; }
    .proof-thumbnail:hover { transform: scale(1.1); }
    .lightbox { display: none; position: fixed; z-index: 999; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); text-align: center; padding-top: 50px; }
    .lightbox:target { display: block; }
    .lightbox img { max-width: 90%; max-height: 80%; margin: auto; border: 3px solid white; border-radius: 5px; }
    .lightbox .close { position: absolute; top: 15px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; text-decoration: none; transition: 0.3s; }
    .lightbox .close:hover { color: #bbb; }
</style>
</head><body><div class="container">
<div class="admin-wrapper">
    <aside class="admin-sidebar"><?php require_once '_menu.php'; ?></aside>
    <main class="admin-content">
        <h1>Urusan Pesanan</h1>
        <div class="card">
            <div class="pagination"><span>Halaman <?=$page?> / <?=$pages?></span> <?php if($page>1):?><a href="?page=<?=$page-1?>">&laquo; Sebelum</a><?php endif;?> <?php if($page<$pages):?><a href="?page=<?=$page+1?>">Seterusnya &raquo;</a><?php endif;?></div>
            <table>
                <tr><th>ID</th><th>Pelanggan & Butiran Pesanan</th><th>Jumlah</th><th>Status & Tracking</th><th>Bukti Bayaran</th><th>Tindakan</th></tr>
                <?php foreach($rows as $o): ?>
                <tr>
                    <td>#<?=$o['id']?><br><small><?=date('d/m/y H:i', strtotime($o['created_at']))?></small></td>
                    <td>
    <strong><?=e($o['name'])?></strong><br>
    <small><?=e($o['phone'])?></small><br>
    <small style="color: #64748b; font-style: italic;"><?= nl2br(e($o['address'])) ?></small>


    <div style="margin-top: 8px; font-size: 12px; border-top: 1px solid #f3f4f6; padding-top: 6px;">
        <?php
        $details = [];
        // 1. Ambil butiran dari pakej utama
        if (!empty($o['package_description'])) {
            $details[] = '<b>' . e($o['package_description']) . '</b>';
        } else {
            $details[] = e($o['package_name']); // Fallback jika tiada description
        }

        // 2. Tambah butiran Upsell atau Downsell dari Tetapan
        if (strpos($o['package_name'], 'UPSELL') !== false) {
            $details[] = '<b>' . e(setting('UPSELL_CONTENT')) . '</b> (Upsell)';
        }
        if (strpos($o['package_name'], 'DOWNSELL') !== false) {
            $details[] = '<b>' . e(setting('DOWNSELL_CONTENT')) . '</b> (Downsell)';
        }

        // 3. Tambah butiran Order Bump dari Tetapan
        if ($o['order_bump']) {
            $details[] = '<b>' . e(setting('ORDER_BUMP_CONTENT')) . '</b> (Bump)';
        }

        echo '<strong>Butiran:</strong><br>' . implode(' + ', $details);
        ?>
        <br>
        <strong>Bayaran:</strong> <span style="font-weight: bold; color: #1d4ed8;"><?= e($o['payment_method']) ?></span>
    </div>
</td>
                    <td><?=money($o['amount'])?></td>
                    <td><?=e($o['status'])?><br><small><?=e((string)$o['tracking_no'])?></small></td>
                    <td>
                        <?php if (!empty($o['proof_file_path'])): ?>
                            <a href="#proof-<?= $o['id'] ?>">
                                <img src="../<?= e($o['proof_file_path']) ?>" class="proof-thumbnail" alt="Bukti Bayaran">
                            </a>
                            <div class="lightbox" id="proof-<?= $o['id'] ?>">
                                <a href="#" class="close">&times;</a>
                                <img src="../<?= e($o['proof_file_path']) ?>" alt="Bukti Bayaran Penuh">
                            </div>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td>
                        <form method="post" class="action-form">
                            <?=csrf_field()?>
                            <input type="hidden" name="id" value="<?=$o['id']?>">
                            <select name="status"><?php foreach(['Pending','Payment Review','Paid','Shipped','Cancelled'] as $s):?><option value="<?=$s?>" <?=$o['status']===$s?'selected':''?>><?=$s?></option><?php endforeach;?></select>
                            <input name="tracking_no" placeholder="No. Tracking" value="<?=e((string)$o['tracking_no'])?>">
                            <button class="cta">Simpan</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
            <div class="pagination" style="margin-top: 12px;"><span>Halaman <?=$page?> / <?=$pages?></span> <?php if($page>1):?><a href="?page=<?=$page-1?>">&laquo; Sebelum</a><?php endif;?> <?php if($page<$pages):?><a href="?page=<?=$page+1?>">Seterusnya &raquo;</a><?php endif;?></div>
        </div>
    </main>
</div>
</div>
<script>
    // Tetapkan masa dalam milisaat (60000ms = 60 saat = 1 minit)
    const refreshInterval = 30000; 

    setTimeout(function() {
        // Arahan untuk muat semula halaman
        window.location.reload();
    }, refreshInterval);
</script>
</body>
</html>

</body></html>