<?php
date_default_timezone_set('Asia/Jakarta');
session_start();
error_log('DEBUG: MASUK KE FILE cek_transaction.php');
require_once(__DIR__ . '/../config/db_config.php');
require_once __DIR__ . '/../models/Order.php';

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

function formatRupiah($amount) {
    return 'Rp ' . number_format($amount, 0, ',', '.');
}

function getOrderItemsStatus($items) {
    if (empty($items)) return '-';
    $statuses = array_column($items, 'status');
    if (count(array_unique($statuses)) === 1) {
        return $statuses[0];
    }
    if (in_array('pending', $statuses)) return 'pending';
    if (in_array('rejected', $statuses)) return 'rejected';
    if (in_array('verified', $statuses)) return 'verified';
    return '-';
}

$db = getDbConnection();
$user_orders = [];
$order_items_map = [];
if ($db) {
    $stmt = $db->prepare("SELECT * FROM orders WHERE user_id = :user_id ORDER BY created_at DESC");
    $stmt->bindParam(':user_id', $_SESSION['user_id']);
    $stmt->execute();
    $user_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // Ambil semua order_id
    $order_ids = array_column($user_orders, 'order_id');
    if (!empty($order_ids)) {
        $in = str_repeat('?,', count($order_ids) - 1) . '?';
        $stmt2 = $db->prepare("SELECT * FROM order_items WHERE order_id IN ($in)");
        $stmt2->execute($order_ids);
        $items = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        foreach ($items as $item) {
            $order_items_map[$item['order_id']][] = $item;
        }
    }
}

if (empty($user_orders)) {
    error_log('DEBUG: user_orders KOSONG untuk user_id: ' . $_SESSION['user_id']);
}

$expire_minutes = 1;
$orderObj = new Order();
foreach ($user_orders as &$order) {
    error_log('DEBUG: Cek order_code: ' . $order['order_code'] . ' | status: ' . $order['status'] . ' | created_at: ' . $order['created_at'] . ' | now: ' . date('Y-m-d H:i:s'));
    $created_at = strtotime($order['created_at']);
    if (time() - $created_at > $expire_minutes * 60 && $order['status'] === 'pending') {
        if ($orderObj->getOrderByOrderCode($order['order_code'])) {
            error_log('DEBUG: Akan update status expired untuk order_code: ' . $order['order_code'] . ' | order_id: ' . $orderObj->order_id);
            if ($orderObj->updateStatus('expired')) {
                error_log('DEBUG: Sukses update status expired untuk order_id: ' . $orderObj->order_id);
                $order['status'] = 'expired';
            } else {
                error_log('ERROR: Gagal update status expired untuk order_id: ' . $orderObj->order_id);
            }
        } else {
            error_log('ERROR: getOrderByOrderCode gagal untuk order_code: ' . $order['order_code']);
        }
    }
}

// Filter user_orders agar hanya satu baris per order_code (tampilkan juga expired, hanya skip cancelled)
$unique_orders = [];
foreach ($user_orders as $order) {
    if ($order['status'] === 'cancelled') continue;
    if (!isset($unique_orders[$order['order_code']])) {
        $unique_orders[$order['order_code']] = $order;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cek Transaction - Riwayat Pembelian</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  

   
    <div class="container py-5">
        <h1 class="mb-4">Riwayat Pembelian Anda</h1>
        <?php if (!empty($unique_orders)): ?>
            <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Kode Pesanan</th>
                        <th>Tanggal</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Invoice</th>
                        <th>Produk Dibeli</th>
                        <th>Pembayaran</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($unique_orders as $order): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($order['order_code']); ?></td>
                            <td><?php echo date('d/m/Y H:i', strtotime($order['created_at'])); ?></td>
                            <td><?php echo formatRupiah($order['total_amount']); ?></td>
                            
                            <td>
                                <?php
                                $item_status = isset($order_items_map[$order['order_id']]) ? getOrderItemsStatus($order_items_map[$order['order_id']]) : '-';
                                echo htmlspecialchars($item_status);
                                ?>
                            </td>
                            <td>
                                <?php
                                if ($item_status === 'verified') {
                                  echo '<a href="invoice.php?order_id=' . urlencode($order['order_code']) . '" class="btn btn-sm btn-primary" target="_blank">Invoice</a>';
                                } else {
                                  echo '<span class="badge bg-secondary">Tidak tersedia</span>';
                                }
                              ?>
                            </td>
                            <td>
                                <?php if (!empty($order_items_map[$order['order_id']])): ?>
                                    <ul class="mb-0">
                                        <?php foreach ($order_items_map[$order['order_id']] as $item): ?>
                                            <li>
                                                <?php echo htmlspecialchars($item['product_name']); ?> x<?php echo $item['quantity']; ?> (<?php echo formatRupiah($item['subtotal']); ?>)
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                // Kolom Pembayaran: tampilkan Bayar Sekarang atau Pesanan hangus
                                $item_status = isset($order_items_map[$order['order_id']]) ? getOrderItemsStatus($order_items_map[$order['order_id']]) : '-';
                                $is_expired = ($order['status'] === 'expired');
                                if ($item_status === 'pending' && !$is_expired) {
                                  echo '<a href="payment_instruction.php?order_id=' . urlencode($order['order_code']) . '&method=manual" class="btn btn-sm btn-success">Bayar Sekarang</a>';
                                } elseif ($is_expired && $item_status === 'pending') {
                                  echo '<span class="badge bg-danger">Pesanan hangus</span>';
                                } else {
                                  echo '<span class="badge bg-secondary">-</span>';
                                }
                              ?>
                            </td>
                            <td>
                                <?php
                                // Tampilkan status utama order
                                $status_map = [
                                    'pending' => 'Menunggu Pembayaran',
                                    'paid' => 'Sudah Dibayar',
                                    'processing' => 'Sedang Diproses',
                                    'shipped' => 'Sedang Dikirim',
                                    'delivered' => 'Dikirim/Siap Diterima',
                                    'completed' => 'Selesai',
                                    'cancelled' => 'Dibatalkan',
                                    'expired' => 'Hangus'
                                ];
                                echo htmlspecialchars($status_map[$order['status']] ?? $order['status']);
                                ?>
                            </td>
                            <td>
                                <?php
                                // Kolom Aksi: hanya fokus pada status orders
                                switch ($order['status']) {
                                    case 'delivered':
                                        echo '<button class="btn btn-success btn-sm pesanan-diterima-btn" data-order="' . htmlspecialchars($order['order_code']) . '">Pesanan Diterima</button>';
                                        break;
                                    case 'completed':
                                        echo '<span class="badge bg-success">Selesai</span>';
                                        break;
                                    case 'processing':
                                        echo '<span class="badge bg-info text-dark">Sedang Diproses</span>';
                                        break;
                                    case 'shipped':
                                        echo '<span class="badge bg-primary">Pesanan Sedang Dikirim</span>';
                                        break;
                                    case 'cancelled':
                                        echo '<span class="badge bg-danger">Dibatalkan</span>';
                                        break;
                                    case 'expired':
                                        echo '<span class="badge bg-secondary">Pesanan Hangus</span>';
                                        break;
                                    default:
                                        echo '<span class="badge bg-secondary">-</span>';
                                }
                              ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
            <p class="text-muted">Belum ada riwayat pembelian.</p>
        <?php endif; ?>
        <a href="dashboard.php" class="btn btn-secondary mt-4">Kembali ke Dashboard</a>
    </div>
    <script>
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.pesanan-diterima-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var orderCode = this.getAttribute('data-order');
      var button = this;
      fetch('update_order_status.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'order_code=' + encodeURIComponent(orderCode) + '&new_status=delivered'
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          button.outerHTML = '<span class="badge bg-success">Selesai</span>';
        } else {
          alert('Gagal update status: ' + (data.message || ''));
        }
      });
    });
  });
});
</script>
</body>
</html> 