<?php
require_once '../includes/config.php';

// Check if user is logged in
if (!isUserLoggedIn()) {
    redirect(SITE_URL . 'user/login.php');
}

// Get order ID
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_id = $_SESSION['user_id'];

if ($order_id <= 0) {
    redirect(SITE_URL . 'user/orders.php');
}

// Handle payment proof upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_payment_proof'])) {
    $payment_message = '';
    
    // Check if file was uploaded without errors
    if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === 0) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
        $max_size = 2 * 1024 * 1024; // 2MB
        
        $file_type = $_FILES['payment_proof']['type'];
        $file_size = $_FILES['payment_proof']['size'];
        
        if (!in_array($file_type, $allowed_types)) {
            $payment_message = '<div class="alert alert-danger">Hanya file JPG dan PNG yang diperbolehkan.</div>';
        } elseif ($file_size > $max_size) {
            $payment_message = '<div class="alert alert-danger">Ukuran file maksimal 2MB.</div>';
        } else {
            // Create directory if not exists
            $upload_dir = '../uploads/payments/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            // Generate unique filename
            $file_ext = pathinfo($_FILES['payment_proof']['name'], PATHINFO_EXTENSION);
            $file_name = 'payment_' . $order_id . '_' . time() . '.' . $file_ext;
            $target_file = $upload_dir . $file_name;
            
            // Upload file
            if (move_uploaded_file($_FILES['payment_proof']['tmp_name'], $target_file)) {
                try {
                    $conn = connectDB();
                    
                    // Check if payment_proof column exists, if not, add it
                    $stmt = $conn->prepare("SHOW COLUMNS FROM orders LIKE 'payment_proof'");
                    $stmt->execute();
                    if ($stmt->rowCount() === 0) {
                        $stmt = $conn->prepare("ALTER TABLE orders ADD payment_proof VARCHAR(255) NULL");
                        $stmt->execute();
                    }
                    
                    // Update order with payment proof
                    $relative_path = 'uploads/payments/' . $file_name;
                    $stmt = $conn->prepare("UPDATE orders SET payment_proof = :payment_proof, status = 'processing' WHERE order_id = :order_id AND user_id = :user_id");
                    $stmt->bindParam(':payment_proof', $relative_path);
                    $stmt->bindParam(':order_id', $order_id);
                    $stmt->bindParam(':user_id', $user_id);
                    $stmt->execute();
                    
                    $payment_message = '<div class="alert alert-success">Bukti pembayaran berhasil diunggah dan sedang diproses.</div>';
                    
                    // Refresh order data
                    $stmt = $conn->prepare("SELECT * FROM orders WHERE order_id = :order_id AND user_id = :user_id");
                    $stmt->bindParam(':order_id', $order_id);
                    $stmt->bindParam(':user_id', $user_id);
                    $stmt->execute();
                    $order = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                } catch (PDOException $e) {
                    $payment_message = '<div class="alert alert-danger">Kesalahan: ' . $e->getMessage() . '</div>';
                }
            } else {
                $payment_message = '<div class="alert alert-danger">Gagal mengunggah file. Silakan coba lagi.</div>';
            }
        }
    } else {
        $payment_message = '<div class="alert alert-danger">Silakan pilih file bukti pembayaran.</div>';
    }
}

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 AND o.user_id = :user_id");
    $stmt->bindParam(':order_id', $order_id);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // If order not found or doesn't belong to user
    if (!$order) {
        redirect(SITE_URL . 'user/orders.php');
    }
    
    // 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);
    
    $pageTitle = "Detail Pesanan #" . $order_id;
    
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

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

<div class="order-detail-page">
    <div class="breadcrumb">
        <a href="<?php echo SITE_URL; ?>">Beranda</a> &gt; 
        <a href="<?php echo SITE_URL; ?>user/orders.php">Pesanan Saya</a> &gt; 
        <span>Detail Pesanan #<?php echo $order_id; ?></span>
    </div>
    
    <h1>Detail Pesanan #<?php echo $order_id; ?></h1>
    
    <?php if (isset($payment_message)) echo $payment_message; ?>
    
    <?php if (isset($error)): ?>
        <p class="error"><?php echo $error; ?></p>
    <?php else: ?>
        <div class="order-detail-container">
            <div class="order-info-section">
                <div class="order-status-bar">
                    <div class="status-label">Status Pesanan:</div>
                    <div class="status-value status-<?php echo $order['status']; ?>">
                        <?php 
                        switch($order['status']) {
                            case 'pending': echo 'Menunggu Pembayaran'; break;
                            case 'processing': echo 'Diproses'; break;
                            case 'shipped': echo 'Dikirim'; break;
                            case 'delivered': echo 'Terkirim'; break;
                            case 'cancelled': echo 'Dibatalkan'; break;
                            default: echo $order['status']; break;
                        }
                        ?>
                    </div>
                </div>
                
                <div class="order-meta">
                    <div class="order-date">
                        <strong>Tanggal Pesanan:</strong> <?php echo date('d-m-Y H:i', strtotime($order['created_at'])); ?>
                    </div>
                    <div class="order-total">
                        <strong>Total Pembayaran:</strong> Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?>
                    </div>
                </div>
                
                <div class="shipping-details">
                    <h3><i class="fas fa-shipping-fast"></i> Detail Pengiriman</h3>
                    <p><strong>Nama:</strong> <?php echo $order['name']; ?></p>
                    <p><strong>Alamat:</strong> <?php echo $order['address']; ?></p>
                    <p><strong>Email:</strong> <?php echo $order['email']; ?></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>
                
                <?php if ($order['status'] == 'pending'): ?>
                <div class="payment-info">
                    <h3><i class="fas fa-credit-card"></i> Informasi Pembayaran</h3>
                    <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 Anda dalam keterangan pembayaran</p>
                    
                    <div class="payment-proof-form">
                        <h4><i class="fas fa-upload"></i> Unggah Bukti Pembayaran</h4>
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="payment_proof">Bukti Pembayaran (JPG/PNG maks. 2MB)</label>
                                <input type="file" name="payment_proof" id="payment_proof" required accept=".jpg,.jpeg,.png">
                            </div>
                            <button type="submit" name="upload_payment_proof" class="btn primary-btn">Unggah Bukti Pembayaran</button>
                        </form>
                    </div>
                </div>
                <?php elseif (isset($order['payment_proof']) && !empty($order['payment_proof'])): ?>
                <div class="payment-info">
                    <h3><i class="fas fa-receipt"></i> Bukti Pembayaran</h3>
                    <div class="payment-proof-image">
                        <img src="<?php echo SITE_URL . $order['payment_proof']; ?>" alt="Bukti Pembayaran">
                        <a href="<?php echo SITE_URL . $order['payment_proof']; ?>" target="_blank" class="btn view-full-btn">Lihat Ukuran Penuh</a>
                        
                        <div class="verification-status">
                            <?php if (isset($order['payment_verified_at'])): ?>
                                <div class="status-badge verified">
                                    <i class="fas fa-check-circle"></i> Pembayaran Terverifikasi
                                </div>
                                <?php if (isset($order['payment_notes']) && !empty($order['payment_notes'])): ?>
                                    <div class="verification-notes">
                                        <p><strong>Catatan:</strong> <?php echo htmlspecialchars($order['payment_notes']); ?></p>
                                    </div>
                                <?php endif; ?>
                            <?php elseif (isset($order['payment_rejected_at'])): ?>
                                <div class="status-badge rejected">
                                    <i class="fas fa-times-circle"></i> Pembayaran Ditolak
                                </div>
                                <?php if (isset($order['payment_notes']) && !empty($order['payment_notes'])): ?>
                                    <div class="verification-notes">
                                        <p><strong>Alasan:</strong> <?php echo htmlspecialchars($order['payment_notes']); ?></p>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="status-badge pending">
                                    <i class="fas fa-clock"></i> Menunggu Verifikasi
                                </div>
                                <p class="verification-info">Bukti pembayaran Anda sedang dalam proses verifikasi oleh admin.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="order-items-section">
                <h3><i class="fas fa-box-open"></i> Produk yang Dipesan</h3>
                <div class="order-items">
                    <?php foreach ($orderItems as $item): ?>
                        <div class="order-item">
                            <div class="product-img-small">
                                <?php if ($item['image_path']): ?>
                                    <img src="<?php echo SITE_URL . $item['image_path']; ?>" alt="<?php echo $item['name']; ?>">
                                <?php else: ?>
                                    <img src="<?php echo SITE_URL; ?>assets/img/no-image.jpg" alt="No Image">
                                <?php endif; ?>
                            </div>
                            <div class="item-details">
                                <div class="item-name"><?php echo $item['name']; ?></div>
                                <div class="item-price">Rp <?php echo number_format($item['price'], 0, ',', '.'); ?> x <?php echo $item['quantity']; ?></div>
                                <div class="item-subtotal">Subtotal: Rp <?php echo number_format($item['price'] * $item['quantity'], 0, ',', '.'); ?></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="order-summary">
                    <div class="table-responsive">
                        <table class="summary-table">
                            <tr>
                                <td>Subtotal:</td>
                                <td>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></td>
                            </tr>
                            <tr>
                                <td>Biaya Pengiriman:</td>
                                <td>Gratis</td>
                            </tr>
                            <tr class="total-row">
                                <td>Total:</td>
                                <td>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="order-actions">
            <a href="<?php echo SITE_URL; ?>user/orders.php" class="btn secondary-btn"><i class="fas fa-arrow-left"></i> Kembali ke Daftar Pesanan</a>
            <?php if ($order['status'] == 'delivered'): ?>
                <a href="#" class="btn primary-btn"><i class="fas fa-star"></i> Beri Ulasan</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
/* Order Detail Page Styles */
.order-detail-page {
    padding: 30px 0;
    max-width: 1000px;
    margin: 0 auto;
}

.breadcrumb {
    margin-bottom: 20px;
    font-size: 14px;
    color: #6c757d;
}

.breadcrumb a {
    color: var(--primary-color);
    text-decoration: none;
}

.breadcrumb a:hover {
    text-decoration: underline;
}

.order-detail-page h1 {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 25px;
    color: #333;
    border-bottom: 2px solid #f2f2f2;
    padding-bottom: 10px;
}

.order-detail-container {
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 15px rgba(0,0,0,0.08);
    overflow: hidden;
}

.order-info-section {
    padding: 25px;
    border-bottom: 1px solid #eee;
}

.order-status-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
}

.status-label {
    font-weight: 600;
    margin-right: 10px;
    color: #333;
}

.status-value {
    padding: 8px 15px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 14px;
    display: inline-block;
}

.status-pending {
    background-color: #fff3cd;
    color: #856404;
}

.status-processing {
    background-color: #d1ecf1;
    color: #0c5460;
}

.status-shipped {
    background-color: #cce5ff;
    color: #004085;
}

.status-delivered {
    background-color: #d4edda;
    color: #155724;
}

.status-cancelled {
    background-color: #f8d7da;
    color: #721c24;
}

.order-meta {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
    font-size: 15px;
}

.order-meta div {
    margin-bottom: 10px;
}

.order-meta strong {
    font-weight: 600;
    color: #333;
}

.order-meta .order-total strong {
    color: var(--primary-color);
}

.order-meta .order-total {
    font-size: 16px;
    font-weight: 500;
}

.shipping-details {
    background-color: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.shipping-details h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
    display: flex;
    align-items: center;
}

.shipping-details h3::before {
    content: "\f54f";
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    margin-right: 10px;
    color: var(--primary-color);
}

.shipping-details p {
    margin-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
}

.shipping-details p strong {
    min-width: 120px;
    font-weight: 600;
    color: #555;
}

.payment-info h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
    display: flex;
    align-items: center;
}

.payment-info h3::before {
    content: "\f09d";
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    margin-right: 10px;
    color: var(--primary-color);
}

.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;
}

.bank-details {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin: 15px 0;
    border-left: 3px solid var(--primary-color);
}

.bank-details p {
    margin: 8px 0;
}

.bank-details p strong {
    color: #333;
}

.note {
    font-size: 14px;
    color: #6c757d;
    margin-top: 10px;
    font-style: italic;
}

.order-items-section {
    padding: 25px;
    background-color: #fafafa;
}

.order-items-section h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
    display: flex;
    align-items: center;
}

.order-items-section h3::before {
    content: "\f07a";
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    margin-right: 10px;
    color: var(--primary-color);
}

.order-item {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    padding: 15px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
}

.product-img-small {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;
    margin-right: 15px;
    border: 1px solid #eee;
    flex-shrink: 0;
}

.product-img-small img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.item-details {
    flex-grow: 1;
}

.item-name {
    font-weight: 600;
    margin-bottom: 5px;
    color: #333;
}

.item-price {
    color: #6c757d;
    font-size: 14px;
}

.item-subtotal {
    font-weight: 500;
    color: var(--primary-color);
    margin-top: 5px;
}

.order-summary {
    margin-top: 25px;
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.summary-table {
    width: 100%;
    border-collapse: collapse;
}

.summary-table tr {
    border-bottom: 1px solid #f2f2f2;
}

.summary-table tr:last-child {
    border-bottom: none;
}

.summary-table td {
    padding: 12px 8px;
}

.summary-table td:last-child {
    text-align: right;
    font-weight: 500;
}

.total-row {
    font-weight: 700;
    color: var(--primary-color);
}

.total-row td {
    padding-top: 15px;
}

.payment-proof-form {
    margin-top: 25px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.payment-proof-form h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
}

.payment-proof-image {
    text-align: center;
    margin-top: 15px;
}

.payment-proof-image img {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.order-actions {
    margin-top: 25px;
    display: flex;
    justify-content: space-between;
    gap: 15px;
}

.order-actions .btn {
    flex: 1;
}

@media (max-width: 768px) {
    .order-meta {
        flex-direction: column;
    }
    
    .order-item {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .product-img-small {
        margin-bottom: 15px;
    }
    
    .order-actions {
        flex-direction: column;
    }
}

/* Payment Verification Status Styles */
.verification-status {
    margin-top: 20px;
    text-align: center;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 10px 15px;
    border-radius: 20px;
    font-weight: 600;
    margin-bottom: 10px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.status-badge i {
    margin-right: 8px;
    font-size: 18px;
}

.status-badge.verified {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.status-badge.rejected {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.status-badge.pending {
    background-color: #fff3cd;
    color: #856404;
    border: 1px solid #ffeeba;
}

.verification-notes {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 10px 15px;
    margin-top: 10px;
    border-left: 3px solid #6c757d;
}

.verification-info {
    font-size: 0.9rem;
    color: #6c757d;
    font-style: italic;
}

.view-full-btn {
    display: block;
    margin: 15px auto 0;
    background-color: #6c757d;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 5px;
    text-align: center;
    text-decoration: none;
    transition: background-color 0.3s;
    width: fit-content;
}

.view-full-btn:hover {
    background-color: #5a6268;
}
</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'; ?> 