<?php
require_once __DIR__ . '/includes/db.php';

$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Ambil data pesanan utama
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
$stmt->execute([$order_id]);
$order = $stmt->fetch();

if (!$order) {
    header("Location: index.php");
    exit();
}

$upload_error = '';
$upload_success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['payment_proof'])) {
    $file = $_FILES['payment_proof'];
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'webp'];
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $upload_error = "Terjadi kesalahan saat mengunggah file. Kode error: " . $file['error'];
    } elseif (!in_array($file_extension, $allowed_extensions)) {
        $upload_error = "Format file tidak didukung. Harap unggah gambar JPG, JPEG, PNG, atau WEBP.";
    } elseif ($file['size'] > 5 * 1024 * 1024) { // 5MB
        $upload_error = "Ukuran file terlalu besar. Maksimal ukuran file adalah 5MB.";
    } else {
        $upload_dir = __DIR__ . '/assets/uploads/payment_proofs';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $new_filename = 'proof_' . $order_id . '_' . time() . '.' . $file_extension;
        $dest_path = $upload_dir . '/' . $new_filename;
        
        if (move_uploaded_file($file['tmp_name'], $dest_path)) {
            // Hapus file lama jika ada
            if (!empty($order['payment_proof'])) {
                $old_file = __DIR__ . '/' . $order['payment_proof'];
                if (file_exists($old_file)) {
                    unlink($old_file);
                }
            }
            
            // Simpan path relatif ke DB & set status verifikasi ke unverified (menunggu verifikasi admin)
            $db_path = 'assets/uploads/payment_proofs/' . $new_filename;
            $update_stmt = $db->prepare("UPDATE orders SET payment_proof = ?, payment_status = 'unverified' WHERE id = ?");
            $update_stmt->execute([$db_path, $order_id]);
            
            // Refresh data pesanan
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            $upload_success = "Bukti pembayaran berhasil diunggah!";
        } else {
            $upload_error = "Gagal memindahkan file yang diunggah ke folder tujuan.";
        }
    }
}

// Ambil detail items pesanan
$items_stmt = $db->prepare("
    SELECT oi.*, p.name as product_name, p.image_url 
    FROM order_items oi
    JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
");
$items_stmt->execute([$order_id]);
$order_items = $items_stmt->fetchAll();

$invoice_num = "INV-" . str_pad($order['id'], 6, '0', STR_PAD_LEFT);

// Buat template teks WhatsApp konfirmasi
$wa_number = "6281210006683"; // Nomor WA Toko (0812-1000-6683)
$wa_text = "Halo Toko Kue Edelys, saya ingin mengonfirmasi pesanan saya:\n\n";
$wa_text .= "*Invoice:* " . $invoice_num . "\n";
$wa_text .= "*Nama:* " . $order['customer_name'] . "\n";
$wa_text .= "*Telepon:* " . $order['customer_phone'] . "\n";
$wa_text .= "*Metode Pembayaran:* " . $order['payment_method'] . "\n";
$wa_text .= "*Total:* Rp " . number_format($order['total_price'], 0, ',', '.') . "\n\n";
$wa_text .= "Kue yang dipesan:\n";
foreach ($order_items as $item) {
    $wa_text .= "- " . $item['product_name'] . " (" . $item['quantity'] . " pcs)\n";
}
$wa_text .= "\nMohon diproses ya, terima kasih!";
$wa_url = "https://api.whatsapp.com/send?phone=" . $wa_number . "&text=" . urlencode($wa_text);

$page_title = "Pemesanan Berhasil - Toko Kue Edelys";
require_once __DIR__ . '/includes/header.php';
?>

<main style="margin-top: 2rem;">
    <div class="success-card">
        <?php if (!empty($upload_success)): ?>
            <div style="background-color: rgba(46, 125, 50, 0.1); color: var(--success-color); padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--success-color); margin-bottom: 1.5rem; text-align: left; display: flex; align-items: center; gap: 0.5rem; width: 100%;">
                <i class="fa-solid fa-circle-check"></i> <span><?php echo htmlspecialchars($upload_success); ?></span>
            </div>
        <?php endif; ?>

        <?php if (!empty($upload_error)): ?>
            <div style="background-color: rgba(198, 40, 40, 0.1); color: var(--danger-color); padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--danger-color); margin-bottom: 1.5rem; text-align: left; display: flex; align-items: center; gap: 0.5rem; width: 100%;">
                <i class="fa-solid fa-circle-exclamation"></i> <span><?php echo htmlspecialchars($upload_error); ?></span>
            </div>
        <?php endif; ?>

        <div class="success-icon">
            <i class="fa-solid fa-circle-check"></i>
        </div>
        <h2>Pemesanan Berhasil!</h2>
        <p>Terima kasih telah berbelanja di Toko Kue Edelys. Pesanan Anda telah kami terima dan akan segera kami proses.</p>

        <div class="order-summary-box">
            <h3 style="font-size: 1.2rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1rem; color: var(--text-primary);">
                Rincian Pesanan
            </h3>
            <div style="display: grid; grid-template-columns: 1fr 1.5fr; gap: 0.8rem; font-size: 0.95rem; color: var(--text-secondary);">
                <span>No. Invoice:</span>
                <span class="invoice-number"><?php echo $invoice_num; ?></span>
                
                <span>Nama Penerima:</span>
                <span style="font-weight: 500; color: var(--text-primary);"><?php echo htmlspecialchars($order['customer_name']); ?></span>
                
                <span>No. WhatsApp:</span>
                <span style="font-weight: 500; color: var(--text-primary);"><?php echo htmlspecialchars($order['customer_phone']); ?></span>
                
                <span>Alamat Pengiriman:</span>
                <span style="font-weight: 500; color: var(--text-primary);"><?php echo nl2br(htmlspecialchars($order['customer_address'])); ?></span>

                <span>Tanggal Pesanan:</span>
                <span><?php echo date('d F Y, H:i', strtotime($order['created_at'])); ?> WIB</span>
                
                <span>Metode Pembayaran:</span>
                <span style="font-weight: 600; color: var(--primary-color);"><?php echo htmlspecialchars($order['payment_method']); ?></span>
            </div>

            <div style="margin-top: 1.5rem; border-top: 1px solid var(--border-color); padding-top: 1rem;">
                <h4 style="font-size: 0.95rem; margin-bottom: 0.8rem; color: var(--text-primary);">Detail Item:</h4>
                <ul style="list-style: none; font-size: 0.9rem;">
                    <?php foreach ($order_items as $item): ?>
                        <li style="display: flex; justify-content: space-between; margin-bottom: 0.5rem; color: var(--text-secondary);">
                            <span><?php echo htmlspecialchars($item['product_name']); ?> (x<?php echo $item['quantity']; ?>)</span>
                            <span style="font-weight: 600; color: var(--text-primary);">Rp <?php echo number_format($item['price_at_purchase'] * $item['quantity'], 0, ',', '.'); ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <div style="margin-top: 1rem; border-top: 1px dashed var(--border-color); padding-top: 1rem; display: flex; justify-content: space-between; font-weight: bold; font-size: 1.1rem; color: var(--text-primary);">
                <span>Total Bayar:</span>
                <span style="color: var(--text-primary);">Rp <?php echo number_format($order['total_price'], 0, ',', '.'); ?></span>
            </div>
        </div>

        <!-- Instruksi Pembayaran -->
        <div style="background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 1.5rem; text-align: left; margin-bottom: 2rem; border-top: 4px solid var(--primary-color); box-shadow: var(--shadow-sm);">
            <h3 style="font-size: 1.1rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1rem; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;">
                <i class="fa-solid fa-credit-card" style="color: var(--primary-color);"></i> Instruksi Pembayaran
            </h3>
            <?php if ($order['payment_method'] === 'QRIS'): ?>
                <div style="text-align: center; padding: 0.5rem 0;">
                    <p style="margin-bottom: 1rem; font-size: 0.95rem; color: var(--text-secondary);">Silakan scan kode QRIS di bawah ini untuk menyelesaikan pembayaran Anda:</p>
                    <div style="display: inline-block; background: white; padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--border-color); box-shadow: var(--shadow-sm); margin-bottom: 1rem;">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=Edelys%20Cake%20Order%20<?php echo $order['id']; ?>%20Total%20<?php echo $order['total_price']; ?>" alt="QRIS Code Edelys Cake" style="display: block; width: 200px; height: 200px;">
                    </div>
                    <p style="font-weight: bold; color: var(--text-primary); margin-bottom: 0.2rem;">TOKO KUE EDELYS</p>
                    <p style="font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 1rem;">NMID: ID1020304050607</p>
                    <p style="font-size: 0.85rem; color: var(--text-secondary); background-color: var(--bg-primary); padding: 0.8rem; border-radius: var(--radius-sm); border: 1px solid var(--border-color);">Setelah melakukan pembayaran, mohon simpan bukti pembayaran dan klik tombol WhatsApp di bawah untuk konfirmasi.</p>
                </div>
            <?php else: ?>
                <div style="font-size: 0.95rem; line-height: 1.6;">
                    <p style="margin-bottom: 1rem; color: var(--text-secondary);">Silakan lakukan transfer bank dengan rincian berikut:</p>
                    <div style="background-color: var(--bg-primary); padding: 1.2rem; border-radius: var(--radius-sm); border-left: 4px solid var(--primary-color); border-top: 1px solid var(--border-color); border-right: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color); margin-bottom: 1.2rem;">
                        <div style="display: grid; grid-template-columns: 1fr 2.2fr; gap: 0.6rem; align-items: center;">
                            <span style="color: var(--text-secondary);">Bank:</span>
                            <strong>BCA (Bank Central Asia)</strong>
                            
                            <span style="color: var(--text-secondary);">No. Rekening:</span>
                            <span style="display: flex; align-items: center; gap: 0.5rem;">
                                <strong style="font-size: 1.2rem; color: var(--primary-color); font-family: monospace; letter-spacing: 1px;">7895254879</strong>
                                <button onclick="navigator.clipboard.writeText('7895254879'); alert('Nomor rekening berhasil disalin!');" style="background: var(--primary-color); color: white; border: none; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.75rem; cursor: pointer; transition: 0.2s;"><i class="fa-regular fa-copy"></i> Salin</button>
                            </span>
                            
                            <span style="color: var(--text-secondary);">Atas Nama:</span>
                            <strong>Edelys</strong>
                            
                            <span style="color: var(--text-secondary);">Total Transfer:</span>
                            <strong style="color: var(--text-primary); font-size: 1.05rem;">Rp <?php echo number_format($order['total_price'], 0, ',', '.'); ?></strong>
                        </div>
                    </div>
                    <p style="font-size: 0.85rem; color: var(--text-secondary); background-color: var(--bg-primary); padding: 0.8rem; border-radius: var(--radius-sm); border: 1px solid var(--border-color);">Harap pastikan nominal transfer sesuai dengan total pembayaran di atas agar pesanan dapat langsung diverifikasi.</p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Upload Bukti Pembayaran -->
        <div style="background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 1.5rem; text-align: left; margin-bottom: 2rem; border-top: 4px solid var(--accent-hover); box-shadow: var(--shadow-sm); width: 100%;">
            <h3 style="font-size: 1.1rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1rem; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;">
                <i class="fa-solid fa-file-arrow-up" style="color: var(--accent-hover);"></i> Upload Bukti Pembayaran
            </h3>
            
            <?php if (!empty($order['payment_proof'])): ?>
                <?php $p_status = isset($order['payment_status']) ? $order['payment_status'] : 'unverified'; ?>
                <div style="background-color: var(--bg-primary); padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--border-color); text-align: center; margin-bottom: 1.2rem;">
                    <?php if ($p_status === 'verified'): ?>
                        <p style="color: var(--success-color); font-weight: 600; margin-bottom: 0.5rem; display: flex; align-items: center; justify-content: center; gap: 0.4rem;">
                            <i class="fa-solid fa-circle-check"></i> Bukti Pembayaran Telah Diverifikasi & Lunas
                        </p>
                    <?php elseif ($p_status === 'rejected'): ?>
                        <p style="color: var(--danger-color); font-weight: 600; margin-bottom: 0.5rem; display: flex; align-items: center; justify-content: center; gap: 0.4rem;">
                            <i class="fa-solid fa-circle-exclamation"></i> Bukti Pembayaran Ditolak. Silakan Unggah Ulang Bukti Valid!
                        </p>
                    <?php else: ?>
                        <p style="color: #C58940; font-weight: 600; margin-bottom: 0.5rem; display: flex; align-items: center; justify-content: center; gap: 0.4rem;">
                            <i class="fa-solid fa-clock-rotate-left"></i> Bukti Pembayaran Berhasil Diunggah (Menunggu Verifikasi Admin/Staff)
                        </p>
                    <?php endif; ?>

                    <div style="max-width: 180px; margin: 0.5rem auto 0.8rem auto; border: 1px solid var(--border-color); padding: 0.25rem; background: white; border-radius: 4px; box-shadow: var(--shadow-sm);">
                        <img src="<?php echo htmlspecialchars($order['payment_proof']); ?>" alt="Bukti Pembayaran" style="width: 100%; display: block; object-fit: contain; max-height: 220px;">
                    </div>
                    <a href="<?php echo htmlspecialchars($order['payment_proof']); ?>" target="_blank" style="font-size: 0.85rem; color: var(--primary-color); text-decoration: underline; font-weight: 500;">
                        <i class="fa-solid fa-up-right-from-square"></i> Lihat Gambar Ukuran Penuh
                    </a>
                </div>
            <?php endif; ?>

            <form action="order_success.php?id=<?php echo $order_id; ?>" method="POST" enctype="multipart/form-data" style="margin-bottom: 0;">
                <div style="margin-bottom: 1rem;">
                    <label for="payment_proof" style="display: block; font-size: 0.9rem; color: var(--text-secondary); margin-bottom: 0.5rem; font-weight: 600;">
                        <?php echo !empty($order['payment_proof']) ? 'Ganti Bukti Pembayaran (jika salah upload)' : 'Pilih file gambar bukti pembayaran:'; ?>
                    </label>
                    <input type="file" name="payment_proof" id="payment_proof" accept="image/*" required style="display: block; width: 100%; padding: 0.5rem; border: 1px dashed var(--border-color); border-radius: var(--radius-sm); background-color: var(--bg-primary); font-family: inherit; font-size: 0.9rem; cursor: pointer;">
                    <small style="color: var(--text-secondary); display: block; margin-top: 0.25rem;">Format didukung: JPG, JPEG, PNG, WEBP. Maksimal ukuran file: 5MB.</small>
                </div>
                <button type="submit" class="btn btn-full" style="padding: 0.75rem; font-size: 0.95rem; display: flex; align-items: center; justify-content: center; gap: 0.5rem; height: auto;">
                    <i class="fa-solid fa-cloud-arrow-up"></i> <?php echo !empty($order['payment_proof']) ? 'Unggah Ulang Bukti Baru' : 'Kirim Bukti Pembayaran'; ?>
                </button>
            </form>
        </div>

        <div class="success-actions">
            <a href="<?php echo $wa_url; ?>" target="_blank" class="btn btn-whatsapp">
                <i class="fa-brands fa-whatsapp"></i> Konfirmasi Pembayaran via WhatsApp
            </a>
            <a href="index.php" class="btn btn-secondary" style="margin-left: 0;">
                <i class="fa-solid fa-cookie-bite"></i> Kembali ke Katalog Kue
            </a>
        </div>
    </div>
</main>

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