<?php
// Include database configuration
require_once '../config/db_config.php';

// Check if user is logged in as admin
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// Check if order ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: dashboard.php');
    exit;
}

$order_id = (int) $_GET['id'];
$success_message = '';
$error_message = '';

// Get order details from database
try {
    $db = getDbConnection();
    
    // Get order header
    $stmt = $db->prepare("SELECT * FROM orders WHERE order_id = :id LIMIT 1");
    $stmt->bindParam(':id', $order_id);
    $stmt->execute();
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        $error_message = "Pesanan tidak ditemukan";
    } else {
        // Get order items
        $stmt = $db->prepare("SELECT * FROM order_items WHERE order_id = :id");
        $stmt->bindParam(':id', $order_id);
        $stmt->execute();
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get transactions
        $stmt = $db->prepare("SELECT * FROM transactions WHERE order_id = :id ORDER BY transaction_time DESC");
        $stmt->bindParam(':id', $order_id);
        $stmt->execute();
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    $error_message = "Database error: " . $e->getMessage();
}

// Process status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_status'])) {
    $new_status = $_POST['new_status'];
    $valid_statuses = [ 'processing', 'shipped', 'delivered', 'cancelled'];
    
    if (in_array($new_status, $valid_statuses)) {
        try {
            $stmt = $db->prepare("UPDATE orders SET status = :status WHERE order_id = :id");
            $stmt->bindParam(':status', $new_status);
            $stmt->bindParam(':id', $order_id);
            
            if ($stmt->execute()) {
                $success_message = "Status pesanan berhasil diperbarui";
                // Refresh order data
                $order['status'] = $new_status;
            } else {
                $error_message = "Gagal memperbarui status pesanan";
            }
        } catch (PDOException $e) {
            $error_message = "Database error: " . $e->getMessage();
        }
    } else {
        $error_message = "Status tidak valid";
    }
}

// Proses update nomor resi
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['update_resi']) &&
    isset($_POST['resi']) &&
    isset($order['shipping_label']) &&
    strtolower($order['shipping_label']) === 'jne'
) {
    $new_resi = trim($_POST['resi']);
    try {
        $stmt = $db->prepare("UPDATE orders SET resi = :resi WHERE order_id = :id");
        $stmt->bindParam(':resi', $new_resi);
        $stmt->bindParam(':id', $order_id);
        if ($stmt->execute()) {
            $success_message = "Nomor resi berhasil diperbarui.";
            $order['resi'] = $new_resi;
        } else {
            $error_message = "Gagal memperbarui nomor resi.";
        }
    } catch (PDOException $e) {
        $error_message = "Database error: " . $e->getMessage();
    }
}

// Format currency
function formatRupiah($amount) {
    return 'Rp ' . number_format($amount, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Pesanan - Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-light d-flex flex-column min-vh-100">
  <div class="container-fluid flex-grow-1">
    <div class="row min-vh-100">
      <!-- Sidebar -->
      <div class="col-lg-2 bg-dark text-white p-0">
        <?php include 'admin_sidebar.php'; ?>
      </div>
      <!-- Konten utama -->
      <div class="col-lg-10 p-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
          <h1 class="h3 fw-bold text-secondary">Detail Pesanan</h1>
          <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-2"></i> Kembali</a>
        </div>
        <?php if (!empty($success_message)): ?>
          <div class="alert alert-success" role="alert"><?php echo $success_message; ?></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
          <div class="alert alert-danger" role="alert"><?php echo $error_message; ?></div>
        <?php endif; ?>
        <?php if (isset($order) && $order): ?>
        <!-- Order Information -->
        <div class="card shadow mb-4">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <h2 class="h5 fw-bold mb-0">Informasi Pesanan</h2>
              <?php
                $status_badge = [
                  'paid' => 'bg-success',
                  'processing' => 'bg-info text-dark',
                  'shipped' => 'bg-primary',
                  'delivered' => 'bg-success',
                  'cancelled' => 'bg-danger',
                  'expired' => 'bg-secondary',
                ];
                $badge_class = $status_badge[$order['status']] ?? 'bg-secondary';
              ?>
              <span class="badge <?php echo $badge_class; ?> px-3 py-2 fs-6"> <?php echo ucfirst($order['status']); ?> </span>
            </div>
            <div class="row g-3 mb-2">
              <div class="col-md-6">
                <div class="small text-muted">Kode Pesanan</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['order_code']); ?></div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Tanggal Pesanan</div>
                <div class="fw-semibold"><?php echo date('d M Y H:i', strtotime($order['created_at'])); ?></div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Nama Pelanggan</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['name']); ?></div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Email</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['email']); ?></div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Nomor Telepon</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['phone']); ?></div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Metode Pembayaran</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['payment_method'] ?? 'Midtrans'); ?></div>
              </div>
              <div class="col-12">
                <div class="small text-muted">Alamat</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['address']); ?></div>
              </div>
            </div>
            <!-- Form update resi untuk JNE -->
            <?php if (isset($order['shipping_label']) && strtolower($order['shipping_label']) === 'jne'): ?>
            <div class="border-top pt-3 mt-3">
              <h6 class="fw-bold mb-2">Update Nomor Resi (JNE)</h6>
              <form action="order_detail.php?id=<?php echo $order_id; ?>" method="POST" class="row g-2 align-items-center">
                <div class="col-auto">
                  <input type="text" name="resi" value="<?php echo htmlspecialchars($order['resi'] ?? ''); ?>" placeholder="Masukkan nomor resi JNE" class="form-control" required>
                </div>
                <div class="col-auto">
                  <button type="submit" name="update_resi" class="btn btn-success"><i class="fas fa-save me-2"></i> Simpan Resi</button>
                </div>
              </form>
              <?php if (!empty($order['resi'])): ?>
                <div class="mt-2 small">Nomor resi saat ini: <span class="fw-bold text-primary"><?php echo htmlspecialchars($order['resi']); ?></span></div>
              <?php endif; ?>
            </div>
            <?php endif; ?>
            <!-- Status Update Form -->
            <div class="border-top pt-3 mt-3">
              <h6 class="fw-bold mb-2">Update Status</h6>
              <form action="order_detail.php?id=<?php echo $order_id; ?>" method="POST" class="row g-2 align-items-center">
                <div class="col-auto">
                  <select name="new_status" class="form-select">
                    <option value="processing" <?php echo $order['status'] === 'processing' ? 'selected' : ''; ?>>Processing</option>
                    <option value="shipped" <?php echo $order['status'] === 'shipped' ? 'selected' : ''; ?>>Shipped</option>
                    <option value="delivered" <?php echo $order['status'] === 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                    <option value="cancelled" <?php echo $order['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                  </select>
                </div>
                <div class="col-auto">
                  <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i> Update Status</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <!-- Order Items -->
        <div class="card shadow mb-4">
          <div class="card-body">
            <h2 class="h5 fw-bold mb-3">Item Pesanan</h2>
            <div class="table-responsive">
              <table class="table table-bordered align-middle">
                <thead class="table-light">
                  <tr>
                    <th>Produk</th>
                    <th>Harga</th>
                    <th>Jumlah</th>
                    <th>Subtotal</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($items as $item): ?>
                  <tr>
                    <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                    <td><?php echo formatRupiah($item['product_price']); ?></td>
                    <td><?php echo $item['quantity']; ?></td>
                    <td><?php echo formatRupiah($item['subtotal']); ?></td>
                  </tr>
                  <?php endforeach; ?>
                  <?php if (empty($items)): ?>
                  <tr>
                    <td colspan="4" class="text-center">Tidak ada item dalam pesanan</td>
                  </tr>
                  <?php endif; ?>
                </tbody>
                <tfoot class="table-light">
                  <tr>
                    <td colspan="3" class="text-end">Total</td>
                    <td class="fw-bold"><?php echo formatRupiah($order['total_amount']); ?></td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
        <!-- Payment Transactions -->
        <div class="card shadow mb-4">
          <div class="card-body">
            <h2 class="h5 fw-bold mb-3">Riwayat Transaksi</h2>
            <div class="table-responsive">
              <table class="table table-bordered align-middle">
                <thead class="table-light">
                  <tr>
                    <th>Waktu Transaksi</th>
                    <th>Jumlah</th>
                    <th>Metode</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($transactions as $transaction): ?>
                  <tr>
                    <td><?php echo date('d M Y H:i', strtotime($transaction['transaction_time'])); ?></td>
                    <td><?php echo formatRupiah($transaction['amount']); ?></td>
                    <td><?php echo htmlspecialchars($transaction['midtrans_payment_type'] ?? $transaction['payment_type']); ?></td>
                    <td>
                      <?php
                        $transaction_status = $transaction['midtrans_transaction_status'] ?? '';
                        $status_class = 'bg-secondary';
                        switch ($transaction_status) {
                          case 'settlement':
                          case 'capture':
                            $status_class = 'bg-success';
                            break;
                          case 'pending':
                            $status_class = 'bg-warning text-dark';
                            break;
                          case 'deny':
                          case 'cancel':
                          case 'expire':
                            $status_class = 'bg-danger';
                            break;
                        }
                      ?>
                      <span class="badge <?php echo $status_class; ?> px-2 py-2"> <?php echo ucfirst($transaction_status); ?> </span>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                  <?php if (empty($transactions)): ?>
                  <tr>
                    <td colspan="4" class="text-center">Tidak ada transaksi yang tercatat</td>
                  </tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <!-- Rating -->
        <?php
        // Tampilkan rating hanya jika status delivered dan tabel rating tersedia
        $canShowRatingSection = false;
        $existing_rating = null;
        if ($order['status'] === 'delivered') {
          try {
            $stmt = $db->prepare('SELECT * FROM order_ratings WHERE order_id = :order_id');
            $stmt->bindParam(':order_id', $order_id);
            $stmt->execute();
            $existing_rating = $stmt->fetch(PDO::FETCH_ASSOC);
            $canShowRatingSection = true;
          } catch (PDOException $e) {
            // Jika tabel order_ratings tidak ada, lewati tanpa memunculkan fatal error
            $canShowRatingSection = false;
          }
        }
        if ($canShowRatingSection && !$existing_rating) {
        ?>
        <div class="card shadow mb-4">
          <div class="card-body">
            <h2 class="h5 fw-bold mb-3">Beri Rating Pesanan Ini</h2>
            <form action="../submit_rating.php" method="POST">
              <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
              <div class="mb-3">
                <label class="form-label">Rating (1-5)</label>
                <select name="rating" required class="form-select w-auto d-inline-block">
                  <option value="">Pilih rating</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                </select>
              </div>
              <div class="mb-3">
                <label class="form-label">Ulasan (opsional)</label>
                <textarea name="review" rows="3" class="form-control"></textarea>
              </div>
              <button type="submit" class="btn btn-success">Kirim Rating</button>
            </form>
          </div>
        </div>
        <?php } elseif ($canShowRatingSection) { ?>
        <div class="card shadow mb-4">
          <div class="card-body">
            <h2 class="h5 fw-bold mb-2">Rating Anda</h2>
            <p class="text-warning fs-5 fw-bold mb-1">Rating: <?php echo $existing_rating['rating']; ?>/5</p>
            <?php if (!empty($existing_rating['review'])): ?>
              <p class="fst-italic text-muted">"<?php echo htmlspecialchars($existing_rating['review']); ?>"</p>
            <?php endif; ?>
          </div>
        </div>
        <?php } ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <footer class="bg-white border-top py-4 mt-auto">
    <div class="container d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
      <div class="text-secondary">&copy; <?php echo date('Y'); ?> Baso Alam Admin Dashboard. All rights reserved.</div>
    </div>
  </footer>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>