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

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

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

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

// Handle status update
if (isset($_POST['update_status']) && isset($_POST['status'])) {
    $status = $_POST['status'];
    $allowed_statuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
    
    if (in_array($status, $allowed_statuses)) {
        try {
            $conn = connectDB();
            $stmt = $conn->prepare("UPDATE orders SET status = :status WHERE order_id = :order_id");
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':order_id', $order_id);
            $stmt->execute();
            
            $success = "Status pesanan berhasil diperbarui";
        } catch (PDOException $e) {
            $error = "Kesalahan: " . $e->getMessage();
        }
    }
}

// Handle payment verification
if (isset($_POST['verify_payment'])) {
    try {
        $conn = connectDB();
        $stmt = $conn->prepare("UPDATE orders SET payment_verified_at = NOW(), payment_notes = 'Pembayaran diverifikasi oleh admin' WHERE order_id = :order_id");
        $stmt->bindParam(':order_id', $order_id);
        $stmt->execute();
        
        $success = "Pembayaran berhasil diverifikasi";
    } catch (PDOException $e) {
        $error = "Kesalahan: " . $e->getMessage();
    }
}

// Handle payment rejection
if (isset($_POST['reject_payment'])) {
    $rejection_reason = isset($_POST['rejection_reason']) ? sanitize($_POST['rejection_reason']) : 'Bukti pembayaran tidak valid';
    
    try {
        $conn = connectDB();
        $stmt = $conn->prepare("UPDATE orders SET payment_rejected_at = NOW(), payment_notes = :rejection_reason WHERE order_id = :order_id");
        $stmt->bindParam(':rejection_reason', $rejection_reason);
        $stmt->bindParam(':order_id', $order_id);
        $stmt->execute();
        
        $success = "Pembayaran ditolak";
    } catch (PDOException $e) {
        $error = "Kesalahan: " . $e->getMessage();
    }
}

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 not found
    if (!$order) {
        redirect(SITE_URL . 'admin/orders/index.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 = "Kesalahan: " . $e->getMessage();
}

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

<div class="admin-header">
    <h1>Detail Pesanan #<?php echo $order_id; ?></h1>
    <div class="admin-actions">
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php" class="btn secondary-btn">Kembali ke Daftar Pesanan</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<div class="admin-content-box">
    <div class="order-detail-grid">
        <div class="order-info-card">
            <h3>Informasi Pesanan</h3>
            <div class="order-status-bar">
                <form action="" method="post" id="status-form">
                    <div class="form-group">
                        <label for="status">Status Pesanan:</label>
                        <select name="status" id="status" onchange="this.form.submit()">
                            <option value="pending" <?php echo ($order['status'] == 'pending') ? 'selected' : ''; ?>>Menunggu Pembayaran</option>
                            <option value="processing" <?php echo ($order['status'] == 'processing') ? 'selected' : ''; ?>>Diproses</option>
                            <option value="shipped" <?php echo ($order['status'] == 'shipped') ? 'selected' : ''; ?>>Dikirim</option>
                            <option value="delivered" <?php echo ($order['status'] == 'delivered') ? 'selected' : ''; ?>>Terkirim</option>
                            <option value="cancelled" <?php echo ($order['status'] == 'cancelled') ? 'selected' : ''; ?>>Dibatalkan</option>
                        </select>
                        <input type="hidden" name="update_status" value="1">
                    </div>
                </form>
            </div>
            
            <div class="order-meta">
                <p><strong>ID Pesanan:</strong> #<?php echo $order['order_id']; ?></p>
                <p><strong>Tanggal Pesanan:</strong> <?php echo date('d-m-Y H:i', strtotime($order['created_at'])); ?></p>
                <p><strong>Total Pembayaran:</strong> Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></p>
            </div>
        </div>
        
        <div class="customer-info-card">
            <h3>Informasi Pelanggan</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>
        </div>
        
        <div class="shipping-info-card">
            <h3>Informasi Pengiriman</h3>
            <?php if(isset($order['shipping_method'])): ?>
            <p>
                <strong>Metode Pengiriman:</strong> 
                <?php 
                switch($order['shipping_method']) {
                    case 'regular': echo 'Reguler'; break;
                    case 'gojek': echo '<i class="fas fa-motorcycle"></i> Gojek (GoSend)'; break;
                    case 'grab': echo '<i class="fas fa-motorcycle"></i> 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 '<i class="fas fa-university"></i> Transfer Bank'; break;
                    case 'cod': echo '<i class="fas fa-money-bill"></i> Bayar di Tempat (COD)'; break;
                    default: echo ucfirst($order['payment_method']); break;
                }
                ?>
            </p>
            <?php endif; ?>
        </div>
        
        <?php if (isset($order['payment_proof']) && !empty($order['payment_proof']) && $order['payment_method'] !== 'cod'): ?>
        <div class="payment-proof-card">
            <h3>Bukti Pembayaran</h3>
            <div class="payment-proof-image">
                <img src="<?php echo SITE_URL . $order['payment_proof']; ?>" alt="Bukti Pembayaran">
                <div class="payment-proof-actions">
                    
                    <?php if (!isset($order['payment_verified_at']) && !isset($order['payment_rejected_at'])): ?>
                    <div class="verification-actions">
                        <form action="" method="post" class="verify-payment-form">
                            <input type="hidden" name="verify_payment" value="1">
                            <button type="submit" class="btn verification-btn">
                                <i class="fas fa-check-circle"></i> Verifikasi Pembayaran
                            </button>
                        </form>
                        
                        <form action="" method="post">
                            <input type="hidden" name="reject_payment" value="1">
                            <button type="submit" class="btn rejection-btn">
                                <i class="fas fa-times-circle"></i> Tolak Pembayaran
                            </button>
                        </form>

                        <div class="reject-form" id="rejectForm" style="display: none;">
                            <form action="" method="post">
                                <div class="form-group">
                                    <label for="rejection_reason">Alasan Penolakan:</label>
                                    <textarea name="rejection_reason" id="rejection_reason" required>Bukti pembayaran tidak valid</textarea>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" name="reject_payment" class="btn confirm-reject-btn">
                                        <i class="fas fa-times-circle"></i> Konfirmasi Penolakan
                                    </button>
                                    <button type="button" class="btn cancel-btn" id="cancelRejectBtn">
                                        Batal
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <?php elseif (isset($order['payment_verified_at'])): ?>
                    <div class="payment-verified">
                        <i class="fas fa-check-circle"></i> Pembayaran Terverifikasi
                        <?php if (isset($order['payment_notes'])): ?>
                        <div class="payment-notes">
                            <small><?php echo $order['payment_notes']; ?></small>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php elseif (isset($order['payment_rejected_at'])): ?>
                    <div class="payment-rejected">
                        <i class="fas fa-times-circle"></i> Pembayaran Ditolak
                        <?php if (isset($order['payment_notes'])): ?>
                        <div class="payment-notes">
                            <small><?php echo $order['payment_notes']; ?></small>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="order-items-section">
        <h3>Produk yang Dipesan</h3>
        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Produk</th>
                        <th>Harga</th>
                        <th>Jumlah</th>
                        <th>Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orderItems as $item): ?>
                        <tr>
                            <td>
                                <div class="product-info-cell">
                                    <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>
                                    <span><?php echo $item['name']; ?></span>
                                </div>
                            </td>
                            <td>Rp <?php echo number_format($item['price'], 0, ',', '.'); ?></td>
                            <td><?php echo $item['quantity']; ?></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"><strong>Total:</strong></td>
                        <td><strong>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<style>
    .order-detail-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    
    .order-info-card,
    .customer-info-card,
    .shipping-info-card,
    .payment-proof-card {
        background-color: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .order-info-card h3,
    .customer-info-card h3,
    .shipping-info-card h3,
    .payment-proof-card h3 {
        margin-top: 0;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
        margin-bottom: 15px;
    }
    
    .order-status-bar {
        margin-bottom: 15px;
    }
    
    #status {
        padding: 8px;
        width: 100%;
        border-radius: 4px;
        border: 1px solid #ddd;
    }
    
    .payment-proof-image {
        text-align: center;
    }
    
    .payment-proof-image img {
        max-width: 100%;
        max-height: 300px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    
    .payment-proof-actions {
        margin-top: 10px;
    }
    
    .product-info-cell {
        display: flex;
        align-items: center;
    }
    
    .product-img-small {
        width: 50px;
        height: 50px;
        margin-right: 15px;
        overflow: hidden;
        border-radius: 4px;
        border: 1px solid #ddd;
    }
    
    .product-img-small img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .text-right {
        text-align: right;
    }
    
    .verify-btn {
        background-color: var(--primary-color);
        color: white;
        border: none;
        padding: 8px 15px;
        border-radius: 4px;
        cursor: pointer;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: background-color 0.3s;
        width: 100%;
    }
    
    .verify-btn:hover {
        background-color: var(--secondary-color);
    }
    
    .verify-payment-form {
        width: 100%;
    }
    
    .payment-verified {
        background-color: #d4edda;
        color: #155724;
        padding: 8px 15px;
        border-radius: 4px;
        margin-top: 10px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }
    
    .payment-verified i {
        color: #3c763d;
    }
    
    .verification-actions {
        display: flex;
        gap: 10px;
        margin-top: 15px;
        width: 100%;
    }
    
    .rejection-btn {
        background-color: #2e8540;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: background-color 0.3s;
        flex: 1;
    }
    
    .rejection-btn:hover {
        background-color: #256a33;
    }
    
    .verification-btn {
        background-color: #2e8540;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: background-color 0.3s;
        flex: 1;
    }
    
    .verification-btn:hover {
        background-color: #256a33;
    }
    
    .reject-form {
        margin-top: 10px;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: #f9f9f9;
    }
    
    .reject-form textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        min-height: 80px;
        margin-top: 5px;
    }
    
    .form-actions {
        display: flex;
        gap: 10px;
        margin-top: 10px;
    }
    
    .confirm-reject-btn {
        background-color: #f44336;
        color: white;
    }
    
    .cancel-btn {
        background-color: #757575;
        color: white;
    }
    
    .payment-rejected {
        background-color: #f2dede;
        color: #a94442;
        padding: 8px 15px;
        border-radius: 4px;
        margin-top: 10px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 5px;
    }
    
    .payment-rejected i {
        color: #a94442;
    }
    
    .payment-notes {
        margin-top: 5px;
        font-style: italic;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle rejection form display
    const showRejectFormBtn = document.querySelector('.rejection-btn');
    const rejectForm = document.getElementById('rejectForm');
    const cancelRejectBtn = document.getElementById('cancelRejectBtn');
    
    if (showRejectFormBtn && rejectForm && cancelRejectBtn) {
        showRejectFormBtn.addEventListener('click', function(e) {
            e.preventDefault();
            rejectForm.style.display = 'block';
            showRejectFormBtn.style.display = 'none';
        });
        
        cancelRejectBtn.addEventListener('click', function() {
            rejectForm.style.display = 'none';
            showRejectFormBtn.style.display = 'flex';
        });
    }
});
</script>

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