<?php
require_once '../includes/config.php';
$pageTitle = "Pesanan Berhasil";

// Check if order ID exists in session
if (!isset($_SESSION['order_id'])) {
    redirect(SITE_URL);
}

$order_id = $_SESSION['order_id'];
unset($_SESSION['order_id']); // Clear order ID from session

try {
    $conn = connectDB();
    
    // Get order details
    $stmt = $conn->prepare("SELECT o.*, u.name, u.email, u.phone, u.address 
                           FROM orders o 
                           JOIN users u ON o.user_id = u.user_id 
                           WHERE o.order_id = :order_id");
    $stmt->bindParam(':order_id', $order_id);
    $stmt->execute();
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        redirect(SITE_URL);
    }
    
    // Get order items
    $stmt = $conn->prepare("SELECT oi.*, p.name, p.image_path 
                           FROM order_items oi 
                           JOIN products p ON oi.product_id = p.product_id 
                           WHERE oi.order_id = :order_id");
    $stmt->bindParam(':order_id', $order_id);
    $stmt->execute();
    $orderItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Kesalahan: " . $e->getMessage();
}

include '../includes/header.php';
?>

<div class="success-page">
    <div class="success-container">
        <div class="success-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        
        <h1>Pesanan Berhasil Dibuat!</h1>
        <p>Terima kasih telah berbelanja di <?php echo SITE_NAME; ?></p>
        
        <div class="order-info">
            <div class="order-number">
                <strong>Nomor Pesanan:</strong> #<?php echo $order['order_id']; ?>
            </div>
            <div class="order-date">
                <strong>Tanggal Pesanan:</strong> <?php echo date('d-m-Y H:i', strtotime($order['created_at'])); ?>
            </div>
        </div>
        
        <div class="customer-info">
            <h3>Informasi Pengiriman</h3>
            <p><strong>Nama:</strong> <?php echo $order['name']; ?></p>
            <p><strong>Alamat:</strong> <?php echo $order['address']; ?></p>
            <p><strong>Telepon:</strong> <?php echo $order['phone']; ?></p>
            
            <?php if(isset($order['shipping_method'])): ?>
            <p><strong>Metode Pengiriman:</strong> 
                <?php 
                switch($order['shipping_method']) {
                    case 'regular': echo 'Reguler'; break;
                    case 'gojek': echo 'Gojek (GoSend)'; break;
                    case 'grab': echo 'Grab (GrabExpress)'; break;
                    default: echo ucfirst($order['shipping_method']); break;
                }
                ?>
            </p>
            <?php endif; ?>
            
            <?php if(isset($order['payment_method'])): ?>
            <p><strong>Metode Pembayaran:</strong> 
                <?php 
                switch($order['payment_method']) {
                    case 'transfer': echo 'Transfer Bank'; break;
                    case 'cod': echo 'Bayar di Tempat (COD)'; break;
                    default: echo ucfirst($order['payment_method']); break;
                }
                ?>
            </p>
            <?php endif; ?>
        </div>
        
        <div class="order-summary">
            <h3>Ringkasan Pesanan</h3>
            <div class="table-responsive">
                <table class="order-items">
                    <thead>
                        <tr>
                            <th>Produk</th>
                            <th>Jumlah</th>
                            <th>Harga</th>
                            <th>Subtotal</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orderItems as $item): ?>
                            <tr>
                                <td><?php echo $item['name']; ?></td>
                                <td><?php echo $item['quantity']; ?></td>
                                <td>Rp <?php echo number_format($item['price'], 0, ',', '.'); ?></td>
                                <td>Rp <?php echo number_format($item['price'] * $item['quantity'], 0, ',', '.'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-right">Subtotal Produk</td>
                            <td>
                                <?php 
                                $subtotal = 0;
                                foreach ($orderItems as $item) {
                                    $subtotal += $item['price'] * $item['quantity'];
                                }
                                echo 'Rp ' . number_format($subtotal, 0, ',', '.');
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="3" class="text-right">Biaya Pengiriman</td>
                            <td>
                                <?php 
                                $shippingCost = $order['total_amount'] - $subtotal;
                                echo 'Rp ' . number_format($shippingCost, 0, ',', '.');
                                ?>
                            </td>
                        </tr>
                        <tr class="total-row">
                            <th colspan="3" class="text-right">Total Pembayaran</th>
                            <th>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        
        <div class="payment-instructions">
            <h3>Instruksi Pembayaran</h3>
            
            <?php if(!isset($order['payment_method']) || $order['payment_method'] === 'transfer'): ?>
                <div class="payment-deadline">
                    <i class="fas fa-clock"></i> 
                    <span>Batas Waktu Pembayaran:</span>
                    <div id="countdown-timer" data-created="<?php echo strtotime($order['created_at']); ?>"></div>
                </div>
                <p>Silakan transfer total pembayaran ke rekening berikut:</p>
                <div class="bank-details">
                    <p><strong>Bank Mandiri</strong></p>
                    <p>No. Rekening: 1560019100470</p>
                    <p>Atas Nama: Warung Klontong Rakha</p>
                </div>
                <p class="note">*Harap sertakan nomor pesanan #<?php echo $order['order_id']; ?> dalam keterangan pembayaran</p>
                <p class="note">*Setelah melakukan pembayaran, silakan unggah bukti transfer di halaman detail pesanan</p>
            <?php elseif($order['payment_method'] === 'cod'): ?>
                <div class="cod-details">
                    <p><i class="fas fa-money-bill"></i> Metode pembayaran: <strong>Bayar di Tempat (COD)</strong></p>
                    <p>Siapkan uang tunai sebesar <strong>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></strong> saat pesanan tiba.</p>
                    <p class="note">*Pastikan Anda atau orang yang menerima pesanan memiliki uang pas untuk memudahkan proses pembayaran.</p>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="next-steps">
            <p>Status pesanan Anda akan diperbarui setelah pembayaran dikonfirmasi.</p>
            <p>Anda dapat melihat status pesanan di halaman <a href="<?php echo SITE_URL; ?>user/orders.php">Pesanan Saya</a>.</p>
        </div>
        
        <div class="action-buttons">
            <a href="<?php echo SITE_URL; ?>user/orders.php" class="btn">Lihat Pesanan Saya</a>
            <a href="<?php echo SITE_URL; ?>" class="btn secondary-btn">Kembali ke Beranda</a>
        </div>
    </div>
</div>

<style>
.success-page {
    padding: 30px 0;
}

.success-container {
    max-width: 800px;
    margin: 0 auto;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    padding: 30px;
}

.success-icon {
    text-align: center;
    margin-bottom: 20px;
}

.success-icon i {
    font-size: 60px;
    color: var(--primary-color);
    background-color: rgba(76, 175, 80, 0.1);
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-radius: 50%;
}

.success-container h1 {
    text-align: center;
    color: var(--primary-color);
    font-size: 2rem;
    margin-bottom: 10px;
}

.success-container > p {
    text-align: center;
    font-size: 1.1rem;
    margin-bottom: 30px;
    color: var(--dark-gray);
}

.order-info {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    background-color: var(--light-gray);
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 30px;
}

.customer-info, .order-summary, .payment-instructions, .next-steps {
    margin-bottom: 30px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 20px;
}

.customer-info h3, .order-summary h3, .payment-instructions h3, .next-steps h3 {
    margin-top: 0;
    color: var(--primary-color);
    border-bottom: 1px solid var(--border-color);
    padding-bottom: 10px;
    margin-bottom: 15px;
}

.order-items {
    width: 100%;
    border-collapse: collapse;
}

.order-items th, .order-items td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}

.order-items th {
    background-color: var(--light-gray);
}

.text-right {
    text-align: right !important;
}

.total-row th {
    border-top: 2px solid var(--primary-color);
    color: var(--primary-color);
    font-size: 1.1rem;
}

.bank-details {
    background-color: var(--light-gray);
    padding: 15px;
    border-radius: 8px;
    margin: 15px 0;
}

.note {
    font-size: 0.9rem;
    color: var(--dark-gray);
    font-style: italic;
}

.cod-details {
    background-color: rgba(255, 152, 0, 0.1);
    padding: 15px;
    border-radius: 8px;
    border-left: 4px solid var(--accent-color);
}

.cod-details p {
    margin: 10px 0;
}

.action-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
}

.payment-deadline {
    background-color: rgba(255, 87, 34, 0.1);
    border-left: 4px solid #FF5722;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.payment-deadline i {
    color: #FF5722;
    font-size: 1.2rem;
}

#countdown-timer {
    font-weight: 700;
    color: #FF5722;
    font-size: 1.1rem;
}

@media (max-width: 576px) {
    .order-info {
        flex-direction: column;
        gap: 10px;
    }
    
    .action-buttons {
        flex-direction: column;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get countdown timer element
    const countdownTimer = document.getElementById('countdown-timer');
    
    if (countdownTimer) {
        // Get the order creation timestamp
        const createdTimestamp = parseInt(countdownTimer.getAttribute('data-created'));
        
        // Calculate deadline (24 hours after order creation)
        const deadlineTimestamp = createdTimestamp + (24 * 60 * 60);
        
        // Update the countdown timer every second
        const timerInterval = setInterval(function() {
            // Get current timestamp
            const now = Math.floor(Date.now() / 1000);
            
            // Calculate remaining time
            const remainingTime = deadlineTimestamp - now;
            
            if (remainingTime <= 0) {
                // Deadline passed
                clearInterval(timerInterval);
                countdownTimer.innerHTML = '<span style="color:#721c24;">Waktu pembayaran telah berakhir</span>';
            } else {
                // Calculate hours, minutes, seconds - ensure hours doesn't exceed 23
                const hours = Math.min(23, Math.floor(remainingTime / 3600));
                const minutes = Math.floor((remainingTime % 3600) / 60);
                const seconds = remainingTime % 60;
                
                // Format the countdown timer
                countdownTimer.innerHTML = 
                    hours.toString().padStart(2, '0') + ':' + 
                    minutes.toString().padStart(2, '0') + ':' + 
                    seconds.toString().padStart(2, '0');
            }
        }, 1000);
    }
});
</script>

<?php include '../includes/footer.php'; ?> 