<?php
require '../config.php';
session_start();
require 'navbar.php'; // Ensure this path is correct

if (!isset($_SESSION['user_id'])) {
  header("Location: ../login.php");
  exit;
}

$user_id = $_SESSION['user_id'];

// Check for payment success notification
$payment_success = false;
$payment_info = null;
if (isset($_GET['payment_success']) && $_GET['payment_success'] == '1' && isset($_SESSION['payment_success'])) {
  $payment_success = true;
  $payment_info = $_SESSION['payment_success'];
  unset($_SESSION['payment_success']); // Clear the session variable
}

// DEBUG: Tampilkan informasi debug jika parameter debug=1
if (isset($_GET['debug']) && $_GET['debug'] == '1') {
  echo "<div style='background: #f0f0f0; padding: 20px; margin: 20px; border: 1px solid #ccc;'>";
  echo "<h3>DEBUG INFORMATION</h3>";
  echo "<p><strong>User ID:</strong> " . $user_id . "</p>";
  echo "<p><strong>Session Data:</strong></p>";
  echo "<pre>" . print_r($_SESSION, true) . "</pre>";

  // Test query langsung
  $test_query = "SELECT COUNT(*) as total FROM transaksi WHERE pengguna_id = ?";
  $test_stmt = $conn->prepare($test_query);
  $test_stmt->bind_param("i", $user_id);
  $test_stmt->execute();
  $test_result = $test_stmt->get_result();
  $test_row = $test_result->fetch_assoc();
  echo "<p><strong>Total transaksi untuk user:</strong> " . $test_row['total'] . "</p>";

  // Tampilkan semua transaksi untuk debugging
  $all_query = "SELECT * FROM transaksi WHERE pengguna_id = ? ORDER BY dibuat_pada DESC LIMIT 5";
  $all_stmt = $conn->prepare($all_query);
  $all_stmt->bind_param("i", $user_id);
  $all_stmt->execute();
  $all_result = $all_stmt->get_result();
  echo "<p><strong>Sample transaksi:</strong></p>";
  echo "<table border='1'><tr><th>ID</th><th>Total</th><th>Status</th><th>Tanggal</th></tr>";
  while ($row = $all_result->fetch_assoc()) {
    echo "<tr><td>" . $row['id'] . "</td><td>" . $row['total_harga'] . "</td><td>" . $row['status'] . "</td><td>" . $row['dibuat_pada'] . "</td></tr>";
  }
  echo "</table>";
  echo "</div>";
}

// Ambil filter dari input GET
$tanggal_dari = $_GET['tanggal_dari'] ?? '';
$tanggal_sampai = $_GET['tanggal_sampai'] ?? '';
$status = isset($_GET['status']) ? $_GET['status'] : '';

// Array of valid statuses for the dropdown
$all_statuses = [
  '' => '-- Semua --',
  'menunggu' => 'Menunggu Konfirmasi',
  'dibayar' => 'Sudah Dibayar',
  'dikirim' => 'Sedang Dikirim',
  'selesai' => 'Pesanan Selesai',
  'dibatalkan' => 'Dibatalkan'
];

// Query status pesanan dengan error handling
$status_list = ['menunggu', 'dibayar', 'dikirim', 'selesai', 'dibatalkan'];
$status_counts = [];

foreach ($status_list as $status_item) {
  $stmt = $conn->prepare("SELECT COUNT(*) as jumlah FROM transaksi WHERE pengguna_id = ? AND status = ?");
  if ($stmt) {
    $stmt->bind_param("is", $user_id, $status_item);
    $stmt->execute();
    $result_status = $stmt->get_result();
    if ($result_status) {
      $row_status = $result_status->fetch_assoc();
      $status_counts[$status_item] = $row_status['jumlah'];
    } else {
      $status_counts[$status_item] = 0;
    }
  } else {
    error_log("Error preparing status query: " . $conn->error);
    $status_counts[$status_item] = 0;
  }
}
$status_config = [
  'menunggu' => ['color' => 'warning', 'icon' => 'clock', 'text' => 'Menunggu Konfirmasi'],
  'dibayar' => ['color' => 'success', 'icon' => 'check-circle', 'text' => 'Sudah Dibayar'],
  'dikirim' => ['color' => 'info', 'icon' => 'truck', 'text' => 'Sedang Dikirim'],
  'selesai' => ['color' => 'primary', 'icon' => 'check-double', 'text' => 'Pesanan Selesai'],
  'dibatalkan' => ['color' => 'danger', 'icon' => 'times-circle', 'text' => 'Dibatalkan']
];

// Start building the WHERE clause with prepared statements for security
$where_clauses = ["pengguna_id = ?"];
$params = [$user_id];
$param_types = "i";

if ($tanggal_dari && $tanggal_sampai) {
  $where_clauses[] = "DATE(dibuat_pada) BETWEEN ? AND ?";
  $params[] = $tanggal_dari;
  $params[] = $tanggal_sampai;
  $param_types .= "ss";
} elseif ($tanggal_dari) {
  $where_clauses[] = "DATE(dibuat_pada) >= ?";
  $params[] = $tanggal_dari;
  $param_types .= "s";
} elseif ($tanggal_sampai) {
  $where_clauses[] = "DATE(dibuat_pada) <= ?";
  $params[] = $tanggal_sampai;
  $param_types .= "s";
}

if ($status !== '' && array_key_exists($status, $all_statuses)) {
  $where_clauses[] = "status = ?";
  $params[] = $status;
  $param_types .= "s";
}

$query_where = implode(" AND ", $where_clauses);
$query = "SELECT * FROM transaksi WHERE $query_where ORDER BY dibuat_pada DESC";

// DEBUG: tampilkan user_id dan query
error_log('SESSION user_id: ' . print_r($_SESSION['user_id'], true));
error_log('QUERY: ' . $query);
error_log('PARAMS: ' . print_r($params, true));

// Prepare and execute the query
$stmt = $conn->prepare($query);
if ($stmt === false) {
  die("Prepare failed: " . $conn->error);
}

$stmt->bind_param($param_types, ...$params);
if (!$stmt->execute()) {
  die("Execute failed: " . $stmt->error);
}
$result = $stmt->get_result();

// DEBUG: Log query results
if (isset($_GET['debug']) && $_GET['debug'] == '1') {
  echo "<div style='background: #ffe6e6; padding: 10px; margin: 10px; border: 1px solid #ff9999;'>";
  echo "<p><strong>Final Query:</strong> " . $query . "</p>";
  echo "<p><strong>Parameters:</strong> " . implode(", ", $params) . "</p>";
  echo "<p><strong>Param Types:</strong> " . $param_types . "</p>";
  echo "<p><strong>Results Found:</strong> " . $result->num_rows . "</p>";
  echo "</div>";
}

function formatKodeTransaksi($id, $timestamp)
{
  $tanggal = date('Ymd', strtotime($timestamp));
  return 'TRX-' . $tanggal . '-' . str_pad($id, 4, '0', STR_PAD_LEFT);
}
?>

<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Riwayat Pemesanan - Day Apparel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    /* Global Minimalist Black & White Theme */
    body {
      background-color: #f8f8f8;
      color: #333;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      font-size: 0.95rem;
    }

    .container {
      max-width: 1200px;
      padding-left: 15px;
      padding-right: 15px;
    }

    /* Page Header */
    .page-header {
      text-align: center;
      margin-bottom: 2rem;
    }

    .page-header h2 {
      color: #222;
      font-weight: 700;
      font-size: 2.5rem;
      margin-bottom: 0.5rem;
    }

    .page-header p {
      color: #777;
      font-size: 1.1rem;
    }

    /* Filter Form */
    .filter-card {
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      padding: 2rem;
      margin-bottom: 2rem;
    }

    .filter-card h5 {
      color: #222;
      font-weight: 600;
      margin-bottom: 1.5rem;
      font-size: 1.2rem;
    }

    .form-label {
      font-weight: 500;
      color: #555;
      margin-bottom: 0.5rem;
      font-size: 0.9rem;
    }

    .form-control,
    .form-select {
      border-radius: 8px;
      border: 1px solid #ddd;
      padding: 0.75rem;
      font-size: 0.95rem;
      color: #333;
      box-shadow: none;
      transition: border-color 0.2s ease, box-shadow 0.2s ease;
      height: auto;
    }

    .form-control:focus,
    .form-select:focus {
      border-color: #888;
      box-shadow: 0 0 0 0.25rem rgba(0, 0, 0, 0.1);
    }

    .btn {
      border-radius: 8px;
      font-weight: 500;
      padding: 0.6rem 1.2rem;
      transition: all 0.2s ease-in-out;
      font-size: 0.9rem;
      white-space: nowrap;
    }

    .btn-dark {
      background-color: #333;
      border-color: #333;
      color: #fff;
    }

    .btn-dark:hover {
      background-color: #555;
      border-color: #555;
      color: #fff;
    }

    .btn-outline-secondary {
      color: #666;
      border-color: #666;
      background-color: #fff;
    }

    .btn-outline-secondary:hover {
      background-color: #666;
      color: #fff;
      border-color: #666;
    }

    .btn i {
      margin-right: 0.3rem;
    }

    /* Cards */
    .card {
      border: none;
      border-radius: 12px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      margin-bottom: 1.5rem;
    }

    .card-body {
      padding: 1.5rem;
    }

    .card h5 {
      font-weight: 600;
      margin-bottom: 1rem;
      font-size: 1.1rem;
    }

    /* Status Cards */
    .status-card {
      transition: transform 0.2s ease;
      height: 100%;
    }

    .status-card:hover {
      transform: translateY(-2px);
    }

    /* Transaction Table - Desktop */
    .table-responsive {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      background: #fff;
    }

    .table {
      margin-bottom: 0;
      background-color: #fff;
      border-collapse: separate;
      border-spacing: 0;
      font-size: 0.9rem;
    }

    .table th,
    .table td {
      padding: 1rem;
      vertical-align: middle;
      border-top: 1px solid #eee;
      border-bottom: none;
    }

    .table thead th {
      background-color: #f8f9fa;
      color: #555;
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.75rem;
      letter-spacing: 0.5px;
      white-space: nowrap;
    }

    .table tbody tr:hover {
      background-color: #f5f5f5;
    }

    /* Mobile Transaction Cards */
    .mobile-transaction-card {
      display: none;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      margin-bottom: 1rem;
      padding: 1.5rem;
    }

    .mobile-transaction-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 1rem;
      flex-wrap: wrap;
      gap: 0.5rem;
    }

    .mobile-transaction-id {
      font-weight: 700;
      color: #333;
      font-size: 1rem;
    }

    .mobile-transaction-total {
      font-weight: 600;
      color: #007bff;
      font-size: 1.1rem;
    }

    .mobile-transaction-details {
      border-top: 1px solid #eee;
      padding-top: 1rem;
      margin-top: 1rem;
    }

    .mobile-detail-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.75rem;
      flex-wrap: wrap;
      gap: 0.5rem;
    }

    .mobile-detail-label {
      font-weight: 500;
      color: #666;
      font-size: 0.85rem;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .mobile-detail-value {
      color: #333;
      font-size: 0.9rem;
      text-align: right;
      flex: 1;
      min-width: 120px;
    }

    .mobile-actions {
      border-top: 1px solid #eee;
      padding-top: 1rem;
      margin-top: 1rem;
      display: flex;
      gap: 0.5rem;
      flex-wrap: wrap;
    }

    .mobile-actions .btn {
      font-size: 0.8rem;
      padding: 0.4rem 0.8rem;
      flex: 1;
      min-width: 120px;
    }

    /* Status Badges */
    .status-badge {
      display: inline-block;
      padding: 0.3rem 0.7rem;
      border-radius: 50px;
      font-size: 0.7rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      white-space: nowrap;
    }

    .status-menunggu {
      background-color: #ffecc2;
      color: #b07c00;
    }

    .status-dibayar {
      background-color: #d1f7e0;
      color: #1a7e3d;
    }

    .status-dikirim {
      background-color: #d8edf7;
      color: #0f5c88;
    }

    .status-selesai {
      background-color: #e2eafc;
      color: #4369a8;
    }

    .status-dibatalkan {
      background-color: #ffe0e6;
      color: #a1283d;
    }

    /* Action Links */
    .action-link {
      color: #333;
      text-decoration: none;
      font-weight: 500;
      transition: color 0.2s ease;
      font-size: 0.85rem;
    }

    .action-link:hover {
      color: #000;
      text-decoration: underline;
    }

    /* No Transactions */
    .no-transactions {
      background-color: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      padding: 3rem 2rem;
      text-align: center;
      margin-top: 2rem;
    }
    
    @media (max-width: 500px) {
      .no-transaction{
        max-width: 400;
        object-fit: contain;
      }
    }

    .no-transactions .fas {
      color: #ccc;
      margin-bottom: 1.5rem;
    }

    .no-transactions h4 {
      color: #666;
      margin-bottom: 1rem;
      font-size: 1.5rem;
    }

    .no-transactions p {
      color: #888;
      margin-bottom: 2rem;
    }

    /* Payment Timer */
    .payment-timer {
      background: rgba(220, 53, 69, 0.1);
      padding: 0.3rem 0.6rem;
      border-radius: 6px;
      display: inline-block;
      margin-bottom: 0.5rem;
    }

    /* Custom grid for 5 columns */
    .col-lg-2-4 {
      flex: 0 0 auto;
      width: 20%;
    }

    /* Responsive Design */
    @media (max-width: 1199.98px) {
      .col-lg-2-4 {
        width: 33.333333%;
      }
    }

    @media (max-width: 991.98px) {
      .container {
        padding-left: 10px;
        padding-right: 10px;
      }

      .col-lg-2-4 {
        width: 50%;
      }

      .filter-card {
        padding: 1.5rem;
      }

      .card-body {
        padding: 1.25rem;
      }

      .page-header h2 {
        font-size: 2rem;
      }
    }

    @media (max-width: 767.98px) {
      body {
        font-size: 0.9rem;
      }

      .container {
        padding-left: 8px;
        padding-right: 8px;
      }

      .page-header h2 {
        font-size: 1.75rem;
      }

      .page-header p {
        font-size: 1rem;
      }

      .col-lg-2-4 {
        width: 100%;
      }

      .filter-card {
        padding: 1.25rem;
      }

      .filter-card h5 {
        font-size: 1.1rem;
      }

      .card-body {
        padding: 1rem;
      }

      .card h5 {
        font-size: 1rem;
      }

      /* Hide desktop table, show mobile cards */
      .table-responsive {
        display: none !important;
      }

      @media(max-width: 1200px) and (min-width: 200px) {
        .table-responsive{
          max-width: 800px;
          object-fit: contain;
        }
      }

      .mobile-transaction-card {
        display: block !important;
      }

      /* Quick actions responsive */
      .btn {
        font-size: 0.8rem;
        padding: 0.5rem 0.8rem;
      }

      .btn i {
        margin-right: 0.2rem;
      }

      /* Form elements */
      .form-control,
      .form-select {
        padding: 0.6rem;
        font-size: 0.9rem;
      }

      .form-label {
        font-size: 0.85rem;
      }

      /* No transactions */
      .no-transactions {
        padding: 2rem 1rem;
      }

      .no-transactions h4 {
        font-size: 1.3rem;
      }

      .no-transactions .fas {
        font-size: 3rem;
      }
    }

    @media (max-width: 575.98px) {
      .mobile-transaction-header {
        flex-direction: column;
        align-items: flex-start;
      }

      .mobile-detail-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.25rem;
      }

      .mobile-detail-value {
        text-align: left;
        min-width: auto;
      }

      .mobile-actions .btn {
        min-width: 100px;
        font-size: 0.75rem;
      }

      .status-badge {
        font-size: 0.65rem;
        padding: 0.25rem 0.5rem;
      }
    }

    /* iPad specific styles */
    @media (min-width: 768px) and (max-width: 1024px) {
      .table-responsive {
        overflow-x: auto;
      }

      .table {
        min-width: 800px;
      }

      .table th,
      .table td {
        padding: 0.8rem;
        font-size: 0.85rem;
      }

      .btn {
        font-size: 0.85rem;
        padding: 0.5rem 1rem;
      }
    }

    /* Loading state */
    .loading {
      opacity: 0.6;
      pointer-events: none;
    }

    /* Hover effects for cards */
    .hover-card {
      transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .hover-card:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }

    /* Improve modal responsive */
    @media (max-width: 576px) {
      .modal-dialog {
        margin: 0.5rem;
      }

      .modal-content {
        border-radius: 12px;
      }

      .modal-body {
        padding: 1rem;
      }

      .modal-header {
        padding: 1rem;
      }

      .modal-footer {
        padding: 1rem;
      }
    }
    /* Tambahkan CSS tabel modern dari riwayat.php */
    .table-responsive {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      background: #fff;
    }
    .table {
      margin-bottom: 0;
      background-color: #fff;
      border-collapse: separate;
      border-spacing: 0;
      font-size: 0.9rem;
    }
    .table th,
    .table td {
      padding: 1rem;
      vertical-align: middle;
      border-top: 1px solid #eee;
      border-bottom: none;
    }
    .table thead th {
      background-color: #f8f9fa;
      color: #555;
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.75rem;
      letter-spacing: 0.5px;
      white-space: nowrap;
    }
    .table tbody tr:hover {
      background-color: #f5f5f5;
    }
    /* Tombol Aksi di Tabel Riwayat */
    .table-responsive .action-link {
      display: inline-block;
      padding: 7px 18px;
      border-radius: 8px;
      border: 1.5px solid #2563eb;
      background: #fff;
      color: #2563eb;
      font-weight: 600;
      text-decoration: none;
      transition: all 0.18s cubic-bezier(.4,0,.2,1);
      box-shadow: 0 1px 4px rgba(37,99,235,0.04);
      width: auto;
      text-align: center;
    }
    .table-responsive .action-link:hover {
      background: #2563eb;
      color: #fff;
      box-shadow: 0 2px 8px rgba(37,99,235,0.12);
      border-color: #2563eb;
      text-decoration: none;
    }
    .table-responsive .btn-beri-ulasan {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 7px 18px;
      border-radius: 8px;
      border: none;
      background: linear-gradient(90deg, #fbbf24 0%, #f59e42 100%);
      color: #222;
      font-weight: 700;
      font-size: 1em;
      box-shadow: 0 2px 8px rgba(251,191,36,0.10);
      cursor: pointer;
      transition: all 0.18s cubic-bezier(.4,0,.2,1);
      margin-left: 0;
    }
    .table-responsive .btn-beri-ulasan:hover, 
    .table-responsive .btn-beri-ulasan:focus {
      background: linear-gradient(90deg, #f59e42 0%, #fbbf24 100%);
      color: #111;
      box-shadow: 0 4px 16px rgba(251,191,36,0.18);
      transform: translateY(-2px) scale(1.04);
      outline: none;
    }
    @media (max-width: 768px) {
      .table-responsive .action-link,
      .table-responsive .btn-beri-ulasan {
        padding: 7px 10px;
        font-size: 0.98em;
        margin-bottom: 6px;
        min-width: 90px;
      }
    }
    /* Status Badges */
    .status-badge {
      display: inline-block;
      padding: 0.3rem 0.7rem;
      border-radius: 50px;
      font-size: 0.7rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      white-space: nowrap;
    }
    .status-menunggu {
      background-color: #ffecc2;
      color: #b07c00;
    }
    .status-dibayar {
      background-color: #d1f7e0;
      color: #1a7e3d;
    }
    .status-dikirim {
      background-color: #d8edf7;
      color: #0f5c88;
    }
    .status-selesai {
      background-color: #e2eafc;
      color: #4369a8;
    }
    .status-dibatalkan {
      background-color: #ffe0e6;
      color: #a1283d;
    }
    /* Pastikan tabel tampil di semua device */
    .table-responsive {
      display: block !important;
      width: 100%;
      overflow-x: auto;
    }
    
  </style>
</head>

<body class="bg-light">

  <div class="container py-4">
    <?php if (isset($_SESSION['success_message'])): ?>
      <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?php echo $_SESSION['success_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['error_message'])): ?>
      <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo $_SESSION['error_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

    <?php if ($payment_success && $payment_info): ?>
      <!-- Payment Success Notification -->
      <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4" role="alert" style="background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);">
        <div class="row align-items-center">
          <div class="col-auto">
            <div class="success-icon bg-success text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
              <i class="fas fa-check fa-2x"></i>
            </div>
          </div>
          <div class="col">
            <h5 class="alert-heading fw-bold text-success mb-2">
              <i class="fas fa-check-circle me-2"></i>Pembayaran Berhasil Dikonfirmasi!
            </h5>
            <p class="mb-2">Bukti pembayaran Anda telah diterima dan sedang diproses oleh tim kami.</p>

            <?php if (isset($payment_info['bank_info'])): ?>
              <div class="payment-details mt-3 p-3 bg-white rounded border">
                <h6 class="fw-bold mb-2"><i class="fas fa-receipt me-2 text-primary"></i>Detail Pembayaran:</h6>
                <div class="row">
                  <div class="col-md-6">
                    <small class="text-muted">Bank/E-Wallet:</small>
                    <div class="fw-bold"><?= htmlspecialchars($payment_info['bank_info']['nama']) ?></div>
                  </div>
                  <div class="col-md-6">
                    <small class="text-muted">Nomor Rekening:</small>
                    <div class="fw-bold text-primary"><?= htmlspecialchars($payment_info['bank_info']['no']) ?></div>
                  </div>
                  <div class="col-md-6">
                    <small class="text-muted">Atas Nama:</small>
                    <div><?= htmlspecialchars($payment_info['bank_info']['an']) ?></div>
                  </div>
                  <div class="col-md-6">
                    <small class="text-muted">Total Dibayar:</small>
                    <div class="fw-bold text-success">Rp<?= number_format($payment_info['total']) ?></div>
                  </div>
                </div>
              </div>
            <?php endif; ?>

            <div class="mt-3">
              <small class="text-muted">
                <i class="fas fa-info-circle me-1"></i>
                Pesanan Anda akan diproses dalam 1-2 jam kerja. Anda akan mendapat notifikasi email jika ada update status.
              </small>
            </div>
          </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    <?php endif; ?>

    <!-- Page Header -->
    <div class="page-header">
      <h2><i class="fas fa-history me-3"></i>Riwayat Pemesanan</h2>
      <p>Kelola dan pantau se
        mua pesanan Anda</p>
    </div>

    <!-- AKSI CEPAT -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <div class="row g-2">
              <div class="col-6 col-md-3">
                <a href="/day.apparel/index.php" class="btn btn-outline-primary w-100">
                  <i class="fas fa-store"></i>
                  <span class="d-none d-sm-inline">Lihat </span>Katalog
                </a>
              </div>
              <div class="col-6 col-md-3">
                <a href="riwayat.php" class="btn btn-outline-secondary w-100">
                  <i class="fas fa-history"></i>
                  <span class="d-none d-sm-inline">Riwayat </span>Pesanan
                </a>
              </div>
              <div class="col-6 col-md-3">
                <a href="profile.php" class="btn btn-outline-info w-100">
                  <i class="fas fa-user-edit"></i>
                  <span class="d-none d-sm-inline">Edit </span>Profile
                </a>
              </div>
              <div class="col-6 col-md-3">
                <a href="../logout.php" class="btn btn-outline-danger w-100" onclick="return confirm('Yakin ingin logout?')">
                  <i class="fas fa-sign-out-alt">
                    </i>
                    Logout
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- STATUS PEMESANAN -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="card border-0 shadow-sm">
          <div class="card-body p-4">
            <h5 class="fw-bold text-dark mb-3">
              <i class="fas fa-chart-pie me-2 text-success"></i>
              Status Pemesanan Anda
            </h5>
            <div class="row g-3 justify-content-center">
              <?php foreach (
                $status_list as $status
              ): ?>
                <div class="col-6 col-sm-6 col-lg-4 col-xl-2 animate-on-scroll">
                  <div class="card h-100 border-0 shadow-sm hover-card">
                    <div class="card-body text-center p-3">
                      <div class="mb-2">
                        <i class="fas fa-<?= $status_config[$status]['icon'] ?> fa-2x text-<?= $status_config[$status]['color'] ?>"></i>
                      </div>
                      <h6 class="card-title small text-muted mb-1">
                        <?= $status_config[$status]['text'] ?>
                      </h6>
                      <div class="display-6 fw-bold text-<?= $status_config[$status]['color'] ?>">
                        <?= $status_counts[$status] ?>
                      </div>
                      <?php if ($status_counts[$status] > 0): ?>
                        <small class="text-muted">pesanan</small>
                      <?php else: ?>
                        <small class="text-muted">-</small>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="filter-card">
      <h5 class="mb-4"><i class="fas fa-filter me-2 text-dark"></i>Filter Pesanan</h5>
      <form method="GET" class="row g-3 align-items-end" id="filterForm">
        <div class="col-md-4 col-lg-3">
          <label for="tanggal_dari" class="form-label">Dari Tanggal:</label>
          <input type="date" id="tanggal_dari" name="tanggal_dari"
            class="form-control" value="<?= htmlspecialchars($tanggal_dari) ?>">
        </div>

        <div class="col-md-4 col-lg-3">
          <label for="tanggal_sampai" class="form-label">Sampai Tanggal:</label>
          <input type="date" id="tanggal_sampai" name="tanggal_sampai"
            class="form-control" value="<?= htmlspecialchars($tanggal_sampai) ?>">
        </div>

        <div class="col-md-4 col-lg-3">
          <label for="status" class="form-label">Status:</label>
          <select name="status" id="status" class="form-select">
            <option value="">-- Semua --</option>
            <option value="menunggu" <?= ($status === 'menunggu') ? 'selected' : '' ?>>Menunggu Konfirmasi</option>
            <option value="dibayar" <?= ($status === 'dibayar') ? 'selected' : '' ?>>Sudah Dibayar</option>
            <option value="dikirim" <?= ($status === 'dikirim') ? 'selected' : '' ?>>Sedang Dikirim</option>
            <option value="selesai" <?= ($status === 'selesai') ? 'selected' : '' ?>>Pesanan Selesai</option>
            <option value="dibatalkan" <?= ($status === 'dibatalkan') ? 'selected' : '' ?>>Dibatalkan</option>
          </select>
        </div>

        <div class="col-12 col-lg-3 d-flex justify-content-end">
          <button type="submit" class="btn btn-dark me-2">
            <i class="fas fa-filter"></i> Terapkan Filter
          </button>
          <a href="riwayat.php" class="btn btn-outline-secondary">
            <i class="fas fa-sync-alt"></i> Reset
          </a>
        </div>
      </form>
    </div>

    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>ID Transaksi</th>
            <th>Total</th>
            <th>Status</th>
            <th>Resi</th>
            <th>Bukti Pembayaran</th>
            <th>Waktu</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($result->num_rows > 0): ?>
            <?php while ($row = $result->fetch_assoc()): ?>
              <tr>
                <td><?= htmlspecialchars(formatKodeTransaksi($row['id'], $row['dibuat_pada'])) ?></td>
                <td>Rp<?= number_format($row['total_harga'], 0, ',', '.') ?></td>
                <td>
                  <span class="status-badge status-<?= htmlspecialchars($row['status']) ?>">
                    <?= htmlspecialchars($all_statuses[$row['status']] ?? ucfirst($row['status'])) ?>
                  </span>
                </td>
                <td><?= $row['resi'] ? htmlspecialchars($row['resi']) : '<span class="text-muted">-</span>' ?></td>
                <td>
                  <?php if ($row['bukti_pembayaran']): ?>
                    <a href="../upload/<?= htmlspecialchars($row['bukti_pembayaran']) ?>" target="_blank" class="action-link">Lihat</a>
                  <?php else: ?>
                    <span class="text-muted">Belum Ada</span>
                  <?php endif; ?>
                </td>
                <td><?= date('d M Y H:i', strtotime($row['dibuat_pada'])) ?></td>
                <td class="d-flex flex-column text-align-center">
                  <?php if ($row['status'] === 'menunggu' && !$row['bukti_pembayaran']): ?>
                    <?php
                    $created_time = strtotime($row['dibuat_pada']);
                    $current_time = time();
                    $elapsed_seconds = $current_time - $created_time;
                    $time_limit = 5 * 60; // 5 menit = 300 detik
                    $remaining_seconds = $time_limit - $elapsed_seconds;

                    if ($remaining_seconds > 0):
                      $minutes = 5;
                      $seconds = 0;
                    ?>
                      <div class="payment-timer mb-2">
                        <small class="text-danger fw-bold">
                          <i class="fas fa-clock"></i>
                          <span id="timer-<?= $row['id'] ?>"><?= sprintf('%02d:%02d', $minutes, $seconds) ?></span>
                        </small>
                      </div>
                      <button class="btn btn-sm btn-warning mb-1" onclick="window.location.href='upload_bukti.php?transaksi_id=<?= $row['id'] ?>'">
                        <i class="fas fa-upload"></i> Upload Bukti
                      </button>
                    <?php else: ?>
                      <span class="text-danger small">Waktu habis</span>
                    <?php endif; ?>
                  <?php elseif ($row['status'] === 'dikirim'): ?>
                    <button class="btn btn-sm btn-success mb-1" onclick="confirmSelesai(<?= $row['id'] ?>)" title="Konfirmasi pesanan sudah diterima">
                      <i class="fas fa-check"></i> Pesanan Selesai
                    </button>
                  <?php elseif ($row['status'] === 'selesai'): ?>
                    <button class="btn btn-sm btn-warning mb-1 w-auto" onclick="openReviewModal(<?= $row['id'] ?>)" title="Beri ulasan untuk pesanan ini">
                      <i class="fas fa-star"></i> Beri Ulasan
                    </button>
                  <?php endif; ?>
                  <a href="detail_transaksi.php?id=<?= htmlspecialchars($row['id']) ?>" class="action-link <?= ($row['status'] === 'menunggu' && !$row['bukti_pembayaran'] || $row['status'] === 'dikirim') ? 'd-block mt-1' : '' ?>">Detail</a>
                </td>
              </tr>
            <?php endwhile; ?>
          <?php else: ?>
            <tr>
              <td colspan="7">
                <div class="no-transactions">
                  <i class="fas fa-box-open fa-4x mb-3"></i>
                  <h4>Tidak Ada Transaksi Ditemukan</h4>
                  <p>Coba ubah kriteria filter Anda atau buat pesanan baru.</p>
                  <a href="../index.php" class="btn btn-dark">
                    <i class="fas fa-shopping-bag me-2"></i>Mulai Berbelanja
                  </a>
                </div>
              </td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

  </div>

  <!-- Modal Upload Bukti Pembayaran -->
  <div class="modal fade" id="uploadBuktiModal" tabindex="-1" aria-labelledby="uploadBuktiModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="uploadBuktiModalLabel">Upload Bukti Pembayaran</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form id="uploadBuktiForm" action="upload_bukti.php" method="POST" enctype="multipart/form-data">
          <div class="modal-body">
            <input type="hidden" name="transaksi_id" id="transaksi_id">
            <div class="mb-3">
              <label for="bukti_pembayaran" class="form-label">Pilih File Bukti Pembayaran</label>
              <input type="file" class="form-control" id="bukti_pembayaran" name="bukti_pembayaran" accept="image/*" required>
              <div class="form-text">Format yang diizinkan: JPG, PNG, JPEG. Maksimal 5MB.</div>
            </div>
            <div class="alert alert-info">
              <i class="fas fa-info-circle"></i>
              Pastikan bukti pembayaran jelas dan dapat dibaca dengan baik.
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
            <button type="submit" class="btn btn-primary">Upload Bukti</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Modal Review Produk -->
  <div class="modal fade" id="reviewModal" tabindex="-1" aria-labelledby="reviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="reviewModalLabel">Beri Ulasan Produk</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body" id="reviewModalBody">
          <!-- Content will be loaded dynamically -->
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/auto-cancel.js"></script>

  <script>
    // Fungsi untuk upload bukti pembayaran
    function uploadBukti(transaksiId) {
      document.getElementById('transaksi_id').value = transaksiId;
      const modal = new bootstrap.Modal(document.getElementById('uploadBuktiModal'));
      modal.show();
    }

    // Fungsi untuk membuka modal review
    function openReviewModal(transaksiId) {
      console.log('Opening review modal for transaction:', transaksiId);

      // Show loading state
      document.getElementById('reviewModalBody').innerHTML = '<div class="text-center p-4"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div><div class="mt-2">Memuat produk...</div></div>';

      // Show modal immediately
      const modal = new bootstrap.Modal(document.getElementById('reviewModal'));
      modal.show();

      // Load products from this transaction via AJAX
      fetch('get_transaction_products.php?transaksi_id=' + transaksiId)
        .then(response => {
          console.log('Response status:', response.status);
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.text();
        })
        .then(html => {
          console.log('Received HTML response');
          document.getElementById('reviewModalBody').innerHTML = html;

          // Make sure submitBulkReview function is available globally
          if (typeof window.submitBulkReview === 'undefined') {
            console.log('submitBulkReview function not found, defining it...');
            window.submitBulkReview = function() {
              console.log('Global submitBulkReview called');
              // Add the function logic here if needed
            };
          }
        })
        .catch(error => {
          console.error('Error loading products:', error);
          document.getElementById('reviewModalBody').innerHTML = '<div class="alert alert-danger">Error memuat produk: ' + error.message + '</div>';
        });
    }

    // Define global submitBulkReview function
    window.submitBulkReview = function() {
      console.log('Global submitBulkReview function called');

      const form = document.getElementById('transactionReviewForm');
      if (!form) {
        console.error('Form not found');
        alert('Form tidak ditemukan. Silakan refresh halaman.');
        return;
      }

      console.log('Form found, processing submission');

      // Validate required fields
      const ratings = form.querySelectorAll('input[type="radio"]:checked');
      const textareas = form.querySelectorAll('textarea[required]');
      let isValid = true;

      // Check if all required ratings are selected
      const ratingGroups = form.querySelectorAll('input[type="radio"][required]');
      const uniqueGroups = new Set();
      ratingGroups.forEach(input => uniqueGroups.add(input.name));

      if (ratings.length < uniqueGroups.size) {
        alert('Harap berikan rating untuk semua produk.');
        return;
      }

      // Check if all textareas are filled
      textareas.forEach(textarea => {
        if (!textarea.value.trim()) {
          isValid = false;
        }
      });

      if (!isValid) {
        alert('Harap isi semua field ulasan.');
        return;
      }

      const submitBtn = document.getElementById('submitReviewBtn');
      if (!submitBtn) {
        console.error('Submit button not found');
        alert('Tombol submit tidak ditemukan.');
        return;
      }

      const originalText = submitBtn.innerHTML;

      // Show loading state
      submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengirim...';
      submitBtn.disabled = true;

      // Create FormData
      const formData = new FormData(form);

      // Debug: Log form data
      console.log('Form data being sent:');
      for (let pair of formData.entries()) {
        console.log(pair[0] + ': ' + pair[1]);
      }

      // Send to processing script
      fetch('proses/proses_tambah_ulasan_bulk.php', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: formData
        })
        .then(response => {
          console.log('Response status:', response.status);
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          console.log('Response data:', data);

          // Reset button
          submitBtn.innerHTML = originalText;
          submitBtn.disabled = false;

          if (data.success) {
            alert('Semua ulasan berhasil dikirim! Terima kasih atas feedback Anda.');

            // Close modal
            const modal = bootstrap.Modal.getInstance(document.querySelector('#reviewModal'));
            if (modal) {
              modal.hide();
            }

            // Refresh the page to update review status
            setTimeout(() => {
              window.location.reload();
            }, 1000);

          } else {
            alert('Error: ' + (data.message || 'Gagal mengirim ulasan. Silakan coba lagi.'));
          }
        })
        .catch(error => {
          console.error('Fetch error:', error);

          // Reset button
          submitBtn.innerHTML = originalText;
          submitBtn.disabled = false;

          alert('Terjadi kesalahan saat mengirim ulasan: ' + error.message);
        });
    };

    // Fungsi untuk konfirmasi pesanan selesai
    function confirmSelesai(transaksi_id) {
      if (confirm('Apakah Anda yakin pesanan sudah diterima dan ingin menandai sebagai selesai?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '../proses/proses_selesai_pesanan.php';

        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'transaksi_id';
        input.value = transaksi_id;

        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
      }
    }

    // Timer countdown untuk pesanan menunggu
    function startTimers() {
      const timerElements = document.querySelectorAll('[id^="timer-"]');

      timerElements.forEach(function(element) {
        const transaksiId = element.id.split('-')[1];
        const timerText = element.textContent.trim();

        if (!timerText || timerText === '') return;

        const parts = timerText.split(':');
        if (parts.length !== 2) return;

        let totalSeconds = parseInt(parts[0]) * 60 + parseInt(parts[1]);

        if (isNaN(totalSeconds) || totalSeconds <= 0) return;

        const interval = setInterval(function() {
          totalSeconds--;

          if (totalSeconds <= 0) {
            clearInterval(interval);
            element.textContent = '00:00';

            // Hide upload button and show expired text
            const row = element.closest('tr');
            const uploadBtn = row ? row.querySelector('.btn-warning') : null;
            const expiredSpan = row ? row.querySelector('.text-danger') : null;

            if (uploadBtn) uploadBtn.style.display = 'none';
            if (expiredSpan) expiredSpan.style.display = 'inline';

            // Refresh halaman untuk update status after 2 seconds
            setTimeout(function() {
              location.reload();
            }, 2000);
            return;
          }

          const minutes = Math.floor(totalSeconds / 60);
          const seconds = totalSeconds % 60;
          element.textContent = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
        }, 1000);
      });
    }

    // Optional: Add a loading state when filter is applied
    document.getElementById('filterForm').addEventListener('submit', function() {
      const filterButton = this.querySelector('button[type="submit"]');
      filterButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Memuat...';
      filterButton.disabled = true;
      this.querySelector('.btn-outline-secondary').disabled = true; // Disable reset button too
      document.querySelector('.table-responsive').classList.add('loading'); // Add loading class to table
    });

    // Handle no transactions row spanning properly
    document.addEventListener('DOMContentLoaded', function() {
      const noTransactionsRow = document.querySelector('.no-transactions');
      if (noTransactionsRow) {
        const table = noTransactionsRow.closest('table');
        if (table) {
          const colspanValue = table.querySelectorAll('thead th').length;
          noTransactionsRow.closest('td').setAttribute('colspan', colspanValue);
        }
      }

      // Start timers
      startTimers();
    });
  </script>
  <?php include '../footer.php'; ?>

</body>

</html>