<?php
session_start();
require '../config.php'; // Adjust this path if necessary
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
require '../pelanggan/navbar.php';
$user_id = $_SESSION['user_id'];
$id = (int)($_GET['id'] ?? 0); // Safely get ID, default to 0 if not set

// --- Fetch main transaction details with JOIN to pengguna ---
$stmt_transaksi = $conn->prepare("
    SELECT 
        transaksi.*, 
        pengguna.nama AS nama_pelanggan, 
        pengguna.alamat_lengkap,
        pengguna.provinsi, 
        pengguna.kabupaten_kota, 
        pengguna.kecamatan,
        pengguna.kelurahan
    FROM transaksi 
    JOIN pengguna ON transaksi.pengguna_id = pengguna.id 
    WHERE transaksi.id = ? AND transaksi.pengguna_id = ?
");

if ($stmt_transaksi === false) {
    die("Prepare failed: " . $conn->error);
}

$stmt_transaksi->bind_param("ii", $id, $user_id);
$stmt_transaksi->execute();
$result_transaksi = $stmt_transaksi->get_result();
$transaksi = $result_transaksi->fetch_assoc();


if (!$transaksi) {
    echo "<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'><title>Transaksi Tidak Ditemukan</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css' rel='stylesheet'></head><body class='bg-light'><div class='container py-5 text-center'><div class='alert alert-danger'>Transaksi tidak ditemukan atau Anda tidak memiliki akses.</div><a href='riwayat.php' class='btn btn-primary mt-3'>Kembali ke Riwayat</a></div></body></html>";
    exit;
}

// --- Fetch product details for the transaction using prepared statement ---
$stmt_detail = $conn->prepare("
    SELECT td.*, p.nama, p.harga, up.ukuran
    FROM transaksi_detail td
    JOIN produk p ON td.produk_id = p.id
    JOIN ukuran_produk up ON td.ukuran_id = up.id
    WHERE td.transaksi_id = ?
");
if ($stmt_detail === false) {
    die("Prepare failed: " . $conn->error);
}
$stmt_detail->bind_param("i", $id);
$stmt_detail->execute();
$result_detail = $stmt_detail->get_result();

// Function to format transaction code
function formatKodeTransaksi($id, $timestamp)
{
    $tanggal = date('Ymd', strtotime($timestamp));
    return 'TRX-' . $tanggal . '-' . str_pad($id, 4, '0', STR_PAD_LEFT);
}

// Map status to Bootstrap badge classes and friendly text
$status_map = [
    'menunggu' => ['text' => 'Menunggu Konfirmasi', 'class' => 'warning'],
    'dibayar' => ['text' => 'Sudah Dibayar', 'class' => 'success'],
    'dikirim' => ['text' => 'Sedang Dikirim', 'class' => 'info'],
    'selesai' => ['text' => 'Pesanan Selesai', 'class' => 'primary'],
    'dibatalkan' => ['text' => 'Dibatalkan', 'class' => 'danger'],
    // Add other statuses if you have them
];

// Get status config for current transaction
$current_status_config = $status_map[$transaksi['status']] ?? ['text' => ucfirst($transaksi['status']), 'class' => 'secondary'];
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Transaksi <?= formatKodeTransaksi($transaksi['id'], $transaksi['dibuat_pada']) ?> - Urban Wear</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>
        body {
            background-color: #f8f8f8;
            /* Light gray background */
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            /* Modern sans-serif font */
            color: #333;
            /* Dark gray for general text */
        }

        .container.main-content {
            background-color: #fff;
            /* White background for the main content area */
            border-radius: 12px;
            /* Softly rounded corners */
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
            /* Stronger, softer shadow */
            padding: 40px;
            /* Increased padding */
            margin-top: 30px;
            margin-bottom: 30px;
        }

        h2.page-title {
            font-size: 2.2rem;
            /* Larger, prominent title */
            font-weight: 700;
            /* Bolder */
            color: #222;
            padding-bottom: 20px;
            margin-bottom: 30px;
            position: relative;
            text-align: center;
        }

        h2.page-title::after {
            content: '';
            display: block;
            width: 60px;
            /* Short, subtle divider */
            height: 3px;
            background-color: #333;
            /* Solid black divider */
            margin: 15px auto 0;
            /* Center the divider */
            border-radius: 2px;
        }

        h3 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #333;
            margin-top: 2.5rem;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.75rem;
        }

        .info-item strong {
            color: #444;
            font-weight: 600;
        }

        .info-item span {
            color: #666;
        }

        .info-list p {
            margin-bottom: 0.75rem;
            /* Spacing for each info item */
            font-size: 1.05rem;
        }

        .table {
            border-radius: 8px;
            /* Rounded table corners */
            overflow: hidden;
            /* Ensures border-radius applies */
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            /* Subtle table shadow */
        }

        .table thead th {
            background-color: #f0f0f0;
            /* Light gray header */
            color: #333;
            font-weight: 600;
            border-bottom: 1px solid #dee2e6;
            padding: 1rem;
        }

        .table tbody tr:nth-child(even) {
            background-color: #fdfdfd;
            /* Lighter stripe for readability */
        }

        .table tbody tr:hover {
            background-color: #e9ecef;
            /* Light hover effect */
        }

        .table td {
            padding: 1rem;
            vertical-align: middle;
        }

        .btn {
            padding: 12px 25px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #333;
            color: #fff;
            border: 1px solid #333;
        }

        .btn-primary:hover {
            background-color: #555;
            border-color: #555;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .btn-outline-secondary {
            border-radius: 8px;
            font-weight: 500;
            padding: 12px 25px;
            transition: all 0.2s ease-in-out;
            color: #6c757d;
            border-color: #ddd;
            background-color: #fff;
        }

        .btn-outline-secondary:hover {
            background-color: #6c757d;
            color: #fff;
            border-color: #6c757d;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .badge {
            font-size: 0.85em;
            /* Slightly larger badge */
            padding: 0.6em 0.9em;
            border-radius: 0.5rem;
            vertical-align: middle;
        }

        /* Status specific badge colors (override Bootstrap's lighter variants) */
        .badge.bg-warning {
            background-color: #ffc107 !important;
            color: #333 !important;
        }

        .badge.bg-success {
            background-color: #28a745 !important;
        }

        .badge.bg-info {
            background-color: #17a2b8 !important;
        }

        .badge.bg-primary {
            background-color: #0d6efd !important;
        }

        /* Use Bootstrap 5's default primary */
        .badge.bg-danger {
            background-color: #dc3545 !important;
        }

        /* Responsive adjustments */
        @media (max-width: 767.98px) {
            .container.main-content {
                padding: 25px;
            }

            h2.page-title {
                font-size: 1.8rem;
                margin-bottom: 25px;
            }

            h3 {
                font-size: 1.3rem;
                margin-top: 2rem;
            }

            .btn {
                width: 100%;
                /* Full width buttons on small screens */
                margin-bottom: 10px;
            }

            .btn:last-child {
                margin-bottom: 0;
            }
        }
    </style>
</head>

<body class="bg-light">
    <!-- Alert Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?= $_SESSION['success'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

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

    <div class="container main-content">
        <h2 class="page-title">Detail Transaksi <br><small class="text-muted fw-normal"><?= formatKodeTransaksi($transaksi['id'], $transaksi['dibuat_pada']) ?></small></h2>

        <div class="row mb-4">
            <div class="col-md-6 info-list">
                <p class="info-item"><strong>Status:</strong>
                    <span class="badge bg-<?= $current_status_config['class'] ?>"><?= htmlspecialchars($current_status_config['text']) ?></span>
                </p>
                <p class="info-item"><strong>Tanggal Pesan:</strong> <span><?= date('d M Y, H:i', strtotime($transaksi['dibuat_pada'])) ?> WIB</span></p>
                <p class="info-item"><strong>Total Pembayaran:</strong> <span class="fw-bold fs-5 text-primary">Rp<?= number_format($transaksi['total_harga'], 0, ',', '.') ?></span></p>
                <p class="info-item"><strong>Ongkos Kirim:</strong> <span>Rp<?= number_format($transaksi['ongkos_kirim'], 0, ',', '.') ?></span></p>
                <p class="info-item"><strong>Metode Pembayaran:</strong> <span><?= htmlspecialchars($transaksi['metode_pembayaran'] ?? "Belum di isi") ?></span></p>
            </div>
            <div class="col-md-6 info-list">
                <p class="info-item"><strong>No Resi:</strong>
                    <span><?= $transaksi['resi'] ? htmlspecialchars($transaksi['resi']) : '<span class="text-muted">Belum Tersedia</span>' ?></span>
                </p>

                <p class="info-item"><strong>Alamat Pengiriman:</strong>
                    <span><?= htmlspecialchars($transaksi['alamat_lengkap'] ?? 'Tidak diketahui') ?></span>
                </p>
                <p class="info-item"><strong>Provinsi:</strong>
                    <span><?= htmlspecialchars($transaksi['provinsi'] ?? 'Tidak diketahui') ?></span>
                </p>
                <p class="info-item"><strong>Kabupaten/Kota:</strong>
                    <span><?= htmlspecialchars($transaksi['kabupaten_kota'] ?? 'Tidak diketahui') ?></span>
                </p>
                <p class="info-item"><strong>Kecamatan:</strong>
                    <span><?= htmlspecialchars($transaksi['kecamatan'] ?? 'Tidak diketahui') ?></span>
                </p>
                <p class="info-item"><strong>Kelurahan:</strong>
                    <span><?= htmlspecialchars($transaksi['kelurahan'] ?? 'Tidak diketahui') ?></span>
                </p>
            </div>
        </div>

        <h3 class="mt-5">Produk Dipesan</h3>
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>Nama Produk</th>
                        <th>Ukuran</th>
                        <th>Harga Satuan</th>
                        <th>Jumlah</th>
                        <th>Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($d = $result_detail->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($d['nama']) ?></td>
                            <td><?= htmlspecialchars($d['ukuran']) ?></td>
                            <td>Rp<?= number_format($d['harga'], 0, ',', '.') ?></td>
                            <td><?= $d['jumlah'] ?></td>
                            <td>Rp<?= number_format($d['subtotal'], 0, ',', '.') ?></td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" class="text-end fw-bold">Ongkos Kirim:</td>
                        <td class="fw-bold">Rp<?= number_format($transaksi['ongkos_kirim'], 0, ',', '.') ?></td>
                    </tr>
                    <tr>
                        <td colspan="4" class="text-end fw-bold fs-5">Total Keseluruhan:</td>
                        <td class="fw-bold fs-5 text-primary">Rp<?= number_format($transaksi['total_harga'], 0, ',', '.') ?></td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <h3 class="mt-5">Bukti Pembayaran</h3>
        <div class="card p-3 mb-4 shadow-sm">
            <?php if ($transaksi['bukti_pembayaran']): ?>
                <div class="text-center mb-3">
                    <img src="../upload/<?= htmlspecialchars($transaksi['bukti_pembayaran']) ?>" class="img-fluid rounded" alt="Bukti Pembayaran" style="max-height: 300px; object-fit: contain;">
                </div>
                <p class="text-center mb-0">
                    <a href="../upload/<?= htmlspecialchars($transaksi['bukti_pembayaran']) ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-expand me-2"></i>Lihat Gambar Penuh
                    </a>
                </p>
            <?php else: ?>
                <div class="alert alert-info text-center mb-0" role="alert">
                    <i class="fas fa-info-circle me-2"></i>Belum ada bukti pembayaran diunggah.
                </div>
            <?php endif; ?>
        </div>

        <div class="d-flex justify-content-between align-items-center mt-5 flex-column flex-md-row">
            <a href="riwayat.php" class="btn btn-outline-secondary mb-3 mb-md-0">
                <i class="fas fa-arrow-left me-2"></i>Kembali ke Riwayat
            </a>
            <div class="d-flex gap-2 flex-column flex-sm-row">
                <?php if ($transaksi['status'] === 'dikirim'): ?>
                    <button class="btn btn-success" onclick="confirmSelesai(<?= $transaksi['id'] ?>)">
                        <i class="fas fa-check me-2"></i>Pesanan Selesai
                    </button>
                <?php endif; ?>
                <a href="cetak_invoice.php?id=<?= $id ?>" target="_blank" class="btn btn-primary">
                    <i class="fas fa-print me-2"></i>Cetak Invoice
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 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();
            }
        }
    </script>
    <?php include '../footer.php'; ?>
</body>

</html>