<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/auth.php';

// Custom Fallback Function สำหรับ sanitize()
if (!function_exists('safe_sanitize')) {
    function safe_sanitize($string) {
        if (function_exists('sanitize')) {
            return sanitize($string);
        }
        return htmlspecialchars((string)$string, ENT_QUOTES, 'UTF-8');
    }
}

requireLogin();

try {
    $db = getDBConnection();
    $userId = $_SESSION['user']['id'] ?? 0;
    $orderId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

    if ($orderId > 0) {
        // Single order details view with Timeline
        $stmt = $db->prepare("select * from orders where id = ? and user_id = ?");
        $stmt->execute([$orderId, $userId]);
        $order = $stmt->fetch();

        if (!$order || empty($order)) {
            // Redirect safely if order not found
            $redirectUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') . '/profile.php' : 'profile.php';
            header('Location: ' . $redirectUrl);
            exit;
        }

        $itemStmt = $db->prepare("select * from order_items where order_id = ?");
        $itemStmt->execute([$orderId]);
        $items = $itemStmt->fetchAll();

        if (empty($items)) {
            $items = [];
        }

        $pageTitle = "คำสั่งซื้อ #" . safe_sanitize($order['order_no'] ?? '');
        require_once __DIR__ . '/../includes/header.php';
        ?>

        <div class="card card-custom p-4 my-4">
          <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
              <h3 class="fw-bold mb-1">📦 คำสั่งซื้อ #<?php echo safe_sanitize($order['order_no'] ?? ''); ?></h3>
              <span class="text-muted">วันที่สั่งซื้อ: <?php echo !empty($order['created_at']) ? date('d/m/Y H:i', strtotime($order['created_at'])) : '-'; ?></span>
            </div>
            <?php $siteUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''; ?>
            <a href="<?php echo $siteUrl; ?>/order_detail.php" class="btn btn-outline-secondary rounded-pill">← ย้อนกลับไปดูทั้งหมด</a>
          </div>

          <!-- Timeline Status Progress -->
          <h5 class="fw-bold mb-3">⏱️ สถานะคำสั่งซื้อ (Timeline)</h5>

          <?php
            // นิยาม step แต่ละ step ว่า active เมื่อไร
            $status = strtolower($order['order_status'] ?? 'pending');
            $step2Active = in_array($status, ['processing', 'shipped', 'completed']);
            $step3Active = in_array($status, ['shipped', 'completed']);
            $step4Active = ($status === 'completed');
            $isCancelled = ($status === 'cancelled');

            // ลีปเพื่อใช้ซ้ำใน HTML
            $activeClass = 'bg-success text-white';
            $inactiveClass = $isCancelled ? 'bg-danger text-white' : 'bg-light text-muted border';

            // payment_status: ถ้า completed ให้แสดงว่าชำระแล้ว
            $paymentStatus = strtolower($order['payment_status'] ?? 'pending');
            $payLabel = ($paymentStatus === 'paid' || $step4Active)
                        ? 'ชำระเงินเรียบร้อยแล้ว'
                        : 'กำลังรอแอดมินตรวจสอบสลิป';
          ?>

          <?php if ($isCancelled): ?>
            <div class="alert alert-danger d-flex align-items-center gap-2 mb-3">
              <span class="fs-4">❌</span>
              <div><strong>คำสั่งซื้อนี้ถูกยกเลิกแล้ว</strong><br><small class="text-muted">หากมีข้อสงสัยกรุณาติดต่อฝ่ายสนับสนุน</small></div>
            </div>
          <?php elseif ($step4Active): ?>
            <div class="alert alert-success d-flex align-items-center gap-2 mb-3">
              <span class="fs-4">✅</span>
              <div><strong>จัดส่งสำเร็จ! สินค้าถึงมือคุณเรียบร้อยแล้ว</strong><br><small class="text-muted">ขอบคุณที่ใช้บริการ — มีปัญหาอะไรติดต่อเราได้เลย</small></div>
            </div>
          <?php endif; ?>

          <ul class="timeline my-4">
            <!-- Step 1: รับคำสั่งซื้อ (active เสมอ) -->
            <li class="timeline-item">
              <div class="timeline-icon bg-success text-white">✓</div>
              <h6 class="fw-bold mb-1">รับคำสั่งซื้อแล้ว</h6>
              <small class="text-muted"><?php echo !empty($order['created_at']) ? date('d/m/Y H:i', strtotime($order['created_at'])) : '-'; ?></small>
            </li>

            <!-- Step 2: ตรวจสอบชำระเงิน / เตรียมสินค้า -->
            <li class="timeline-item">
              <div class="timeline-icon <?php echo $step2Active ? $activeClass : $inactiveClass; ?>">
                <?php echo $step2Active ? '✓' : '2'; ?>
              </div>
              <h6 class="fw-bold mb-1">ตรวจสอบการชำระเงิน / เตรียมสินค้า</h6>
              <small class="text-muted"><?php echo $payLabel; ?></small>
            </li>

            <!-- Step 3: กำลังจัดส่งสินค้า -->
            <li class="timeline-item">
              <div class="timeline-icon <?php echo $step3Active ? $activeClass : $inactiveClass; ?>">
                <?php echo $step3Active ? '✓' : '3'; ?>
              </div>
              <h6 class="fw-bold mb-1">กำลังจัดส่งสินค้า</h6>
              <small class="text-muted">
                <?php
                  $tracking = $order['tracking_number'] ?? '';
                  if ($step3Active && $tracking) {
                      echo 'เลขพัสดุ: <strong class="text-primary">' . htmlspecialchars($tracking) . '</strong>';
                  } elseif ($step3Active) {
                      echo 'อยู่ระหว่างจัดส่ง';
                  } else {
                      echo 'รอรับเลขพัสดุ';
                  }
                ?>
              </small>
            </li>

            <!-- Step 4: จัดส่งสำเร็จ -->
            <li class="timeline-item">
              <div class="timeline-icon <?php echo $step4Active ? $activeClass : $inactiveClass; ?>">
                <?php echo $step4Active ? '✓' : '4'; ?>
              </div>
              <h6 class="fw-bold mb-1">จัดส่งสำเร็จ</h6>
              <small class="text-muted">สินค้าถึงมือคุณเรียบร้อยแล้ว</small>
            </li>
          </ul>

          <hr class="my-4">
          <div class="row">
            <div class="col-md-6 mb-3">
              <h6 class="fw-bold">🏠 ที่อยู่สำหรับจัดส่ง:</h6>
              <p class="mb-1"><strong><?php echo safe_sanitize($order['shipping_name'] ?? ''); ?></strong> (<?php echo safe_sanitize($order['shipping_phone'] ?? ''); ?>)</p>
              <p class="text-muted mb-0"><?php echo safe_sanitize($order['shipping_address'] ?? ''); ?></p>
            </div>
            <div class="col-md-6 mb-3">
              <h6 class="fw-bold">💳 วิธีการชำระเงิน:</h6>
              <p class="mb-1">วิธี: <strong><?php echo strtoupper($order['payment_method'] ?? 'unknown'); ?></strong></p>
              <p class="mb-0">สถานะชำระ: 
                <span class="badge <?php
                  // ถ้า completed หรือ shipped ให้แสดงเป็น paid เสมอ
                  $effectivePaid = ($paymentStatus === 'paid' || in_array($status, ['shipped', 'completed']));
                  echo $effectivePaid ? 'bg-success' : 'bg-warning text-dark';
                ?>">
                  <?php echo $effectivePaid ? '✓ PAID' : strtoupper($paymentStatus); ?>
                </span>
              </p>
              <?php if (!empty($order['payment_slip'])): ?>
                <div class="mt-2">
                  <?php
                    $slipUrl = (defined('UPLOAD_URL') ? rtrim(UPLOAD_URL, '/') : '') . '/' . ltrim($order['payment_slip'], '/');
                  ?>
                  <a href="<?php echo safe_sanitize($slipUrl); ?>" target="_blank" class="btn btn-sm btn-outline-info">📄 ดูสลิปที่แนบไว้</a>
                </div>
              <?php endif; ?>
            </div>
          </div>

          <h5 class="fw-bold mt-4 mb-3">🛒 รายการสินค้าที่สั่งซื้อ</h5>
          <table class="table align-middle">
            <thead>
              <tr>
                <th>สินค้า</th>
                <th>รายละเอียด</th>
                <th class="text-center">ราคา</th>
                <th class="text-center">จำนวน</th>
                <th class="text-end">รวม</th>
              </tr>
            </thead>
            <tbody>
              <?php if (!empty($items)): ?>
                <?php foreach ($items as $it): ?>
                  <tr>
                    <td class="fw-bold"><?php echo safe_sanitize($it['product_name'] ?? ''); ?></td>
                    <td><small class="text-muted"><?php echo safe_sanitize($it['variant_info'] ?? '-'); ?></small></td>
                    <td class="text-center">฿<?php echo number_format((float)($it['price'] ?? 0), 2); ?></td>
                    <td class="text-center"><?php echo (int)($it['quantity'] ?? 0); ?></td>
                    <td class="text-end fw-bold">฿<?php echo number_format((float)($it['subtotal'] ?? 0), 2); ?></td>
                  </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <tr>
                    <td colspan="5" class="text-center text-muted py-3">ไม่มีรายการสินค้า</td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>

        <?php
        require_once __DIR__ . '/../includes/footer.php';
        exit;
    }

    // Order List View
    $stmt = $db->prepare("select * from orders where user_id = ? order by created_at desc");
    $stmt->execute([$userId]);
    $orders = $stmt->fetchAll();

    if (empty($orders)) {
        $orders = [];
    }

    $pageTitle = "ประวัติคำสั่งซื้อ";
    require_once __DIR__ . '/../includes/header.php';
    ?>

    <div class="card card-custom p-4 my-4">
      <h3 class="fw-bold mb-4">📦 ประวัติคำสั่งซื้อของฉัน</h3>

      <?php if (empty($orders)): ?>
        <div class="text-center py-5">
          <div class="fs-1">📦</div>
          <h4 class="text-muted mt-2">ยังไม่มีประวัติการสั่งซื้อ</h4>
          <?php $siteUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''; ?>
          <a href="<?php echo $siteUrl; ?>/index.php" class="btn btn-primary-custom rounded-pill mt-2">ไปเลือกซื้อสินค้า</a>
        </div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-hover align-middle">
            <thead>
              <tr>
                <th>เลขคำสั่งซื้อ</th>
                <th>วันที่</th>
                <th>วิธีชำระ</th>
                <th>ยอดรวม</th>
                <th>สถานะออเดอร์</th>
                <th>การจัดการ</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($orders as $o): ?>
                <tr>
                  <td class="fw-bold text-primary">#<?php echo safe_sanitize($o['order_no'] ?? ''); ?></td>
                  <td><?php echo !empty($o['created_at']) ? date('d/m/Y H:i', strtotime($o['created_at'])) : '-'; ?></td>
                  <td><span class="badge bg-secondary"><?php echo strtoupper($o['payment_method'] ?? 'unknown'); ?></span></td>
                  <td class="fw-bold">฿<?php echo number_format((float)($o['total_amount'] ?? 0), 2); ?></td>
                  <td>
                    <?php
                      $ordStatus = strtolower($o['order_status'] ?? '');
                      $badgeClass = 'bg-warning text-dark';
                      if ($ordStatus === 'completed') {
                          $badgeClass = 'bg-success';
                      } elseif ($ordStatus === 'shipped') {
                          $badgeClass = 'bg-info text-dark';
                      } elseif ($ordStatus === 'processing') {
                          $badgeClass = 'bg-primary';
                      } elseif ($ordStatus === 'cancelled') {
                          $badgeClass = 'bg-danger';
                      }
                    ?>
                    <span class="badge <?php echo $badgeClass; ?>">
                      <?php echo strtoupper($ordStatus ?: 'PENDING'); ?>
                    </span>
                  </td>
                  <td>
                    <?php $siteUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''; ?>
                    <a href="<?php echo $siteUrl; ?>/order_detail.php?id=<?php echo (int)($o['id'] ?? 0); ?>" class="btn btn-sm btn-outline-primary rounded-pill">ดูรายละเอียด 🔍</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>

    <?php require_once __DIR__ . '/../includes/footer.php'; ?>

<?php
} catch (PDOException $e) {
    // ดักจับ Error Database 
    $pageTitle = "ระบบขัดข้องชั่วคราว (Database Error)";
    @require_once __DIR__ . '/../includes/header.php';
    ?>
    <div class="container my-5">
        <div class="alert alert-danger shadow-sm border-0">
            <h4 class="alert-heading fw-bold">⚠️ พบข้อผิดพลาดในการเชื่อมต่อฐานข้อมูล</h4>
            <hr>
            <p class="mb-0">ขออภัยในความไม่สะดวก ระบบไม่สามารถดึงข้อมูลคำสั่งซื้อได้ในขณะนี้ กรุณาลองใหม่อีกครั้งในภายหลัง</p>
            <!-- สามารถซ่อน Error Message ใน Production ได้ -->
            <p class="mt-3 mb-0 text-muted"><small><i>Details: <?php echo htmlspecialchars($e->getMessage()); ?></i></small></p>
        </div>
        <?php $siteUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''; ?>
        <a href="<?php echo $siteUrl; ?>/index.php" class="btn btn-primary rounded-pill mt-3">กลับสู่หน้าหลัก</a>
    </div>
    <?php
    @require_once __DIR__ . '/../includes/footer.php';
} catch (Exception $e) {
    // ดักจับ Error ทั่วไป
    $pageTitle = "ระบบขัดข้อง (System Error)";
    @require_once __DIR__ . '/../includes/header.php';
    ?>
    <div class="container my-5">
        <div class="alert alert-danger shadow-sm border-0">
            <h4 class="alert-heading fw-bold">⚠️ เกิดข้อผิดพลาดของระบบ</h4>
            <hr>
            <p class="mb-0">ระบบเกิดข้อผิดพลาดบางประการ: <strong><?php echo htmlspecialchars($e->getMessage()); ?></strong></p>
        </div>
        <?php $siteUrl = defined('SITE_URL') ? rtrim(SITE_URL, '/') : ''; ?>
        <a href="<?php echo $siteUrl; ?>/index.php" class="btn btn-primary rounded-pill mt-3">กลับสู่หน้าหลัก</a>
    </div>
    <?php
    @require_once __DIR__ . '/../includes/footer.php';
}
?>
