<?php
$page_title = "Kelola Pesanan & Verifikasi Bukti Transfer";
$header_title = "Manajemen & Verifikasi Pesanan Pelanggan";
require_once __DIR__ . '/../includes/admin_header.php';

$message = '';
$error = '';

// 1. UPDATE STATUS & VERIFIKASI PEMBAYARAN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $order_id = intval($_POST['order_id']);
    
    // Action A: Verifikasi Pembayaran Khusus
    if ($action === 'verify_payment') {
        $payment_status = $_POST['payment_status']; // 'verified' atau 'rejected' atau 'unverified'
        $auto_process = isset($_POST['auto_process']) ? true : false;
        
        try {
            $db->beginTransaction();
            
            $update_sql = "UPDATE orders SET payment_status = ? WHERE id = ?";
            $db->prepare($update_sql)->execute([$payment_status, $order_id]);
            
            // Jika disetujui & opsi auto_process aktif, ubah status order menjadi 'processing' jika masih 'pending'
            if ($payment_status === 'verified') {
                $status_stmt = $db->prepare("SELECT status FROM orders WHERE id = ?");
                $status_stmt->execute([$order_id]);
                $curr_st = $status_stmt->fetchColumn();
                
                if ($curr_st === 'pending') {
                    $db->prepare("UPDATE orders SET status = 'processing' WHERE id = ?")->execute([$order_id]);
                }
                $message = "Pembayaran untuk Invoice #INV-" . str_pad($order_id, 6, '0', STR_PAD_LEFT) . " berhasil DIVERIFIKASI!";
            } elseif ($payment_status === 'rejected') {
                $message = "Bukti pembayaran Invoice #INV-" . str_pad($order_id, 6, '0', STR_PAD_LEFT) . " telah DITOLAK.";
            } else {
                $message = "Status verifikasi pembayaran diperbarui.";
            }
            
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            $error = "Gagal memproses verifikasi: " . $e->getMessage();
        }
    }
    
    // Action B: Update Status Utama Pesanan
    elseif ($action === 'update_status') {
        $new_status = $_POST['status'];
        
        // Ambil status pesanan saat ini
        $status_stmt = $db->prepare("SELECT status, payment_status FROM orders WHERE id = ?");
        $status_stmt->execute([$order_id]);
        $ord_data = $status_stmt->fetch();
        $current_status = $ord_data ? $ord_data['status'] : null;
        
        if ($current_status && $current_status !== $new_status) {
            $db->beginTransaction();
            try {
                // Ambil rincian item pesanan
                $items_stmt = $db->prepare("SELECT product_id, quantity FROM order_items WHERE order_id = ?");
                $items_stmt->execute([$order_id]);
                $items = $items_stmt->fetchAll();

                // Skenario A: Pesanan dibatalkan (Cancel) -> Kembalikan stok kue ke gudang
                if ($new_status === 'cancelled' && $current_status !== 'cancelled') {
                    $update_stock = $db->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                    $log_stock = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'in', ?)");
                    
                    foreach ($items as $item) {
                        $update_stock->execute([$item['quantity'], $item['product_id']]);
                        $note = "Pengembalian stok - Pembatalan pesanan #" . str_pad($order_id, 5, '0', STR_PAD_LEFT);
                        $log_stock->execute([$item['product_id'], $item['quantity'], $note]);
                    }
                }
                
                // Skenario B: Pesanan diaktifkan kembali dari status Batal -> Potong stok lagi
                elseif ($current_status === 'cancelled' && $new_status !== 'cancelled') {
                    // Cek ketersediaan stok terlebih dahulu
                    foreach ($items as $item) {
                        $check_stock = $db->prepare("SELECT stock, name FROM products WHERE id = ?");
                        $check_stock->execute([$item['product_id']]);
                        $prod = $check_stock->fetch();
                        if ($prod['stock'] < $item['quantity']) {
                            throw new Exception("Gagal mengaktifkan pesanan. Stok kue '" . $prod['name'] . "' tidak cukup (Sisa: " . $prod['stock'] . " pcs, Dibutuhkan: " . $item['quantity'] . " pcs).");
                        }
                    }
                    
                    // Potong stok kembali
                    $update_stock = $db->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
                    $log_stock = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'out', ?)");
                    
                    foreach ($items as $item) {
                        $update_stock->execute([$item['quantity'], $item['product_id']]);
                        $note = "Pengurangan stok ulang - Pengaktifkan kembali pesanan #" . str_pad($order_id, 5, '0', STR_PAD_LEFT);
                        $log_stock->execute([$item['product_id'], -$item['quantity'], $note]);
                    }
                }
                
                // Update status pesanan di database
                $update_order = $db->prepare("UPDATE orders SET status = ? WHERE id = ?");
                $update_order->execute([$new_status, $order_id]);
                
                // Jika status diubah ke completed, otomatis set payment_status = verified
                if ($new_status === 'completed') {
                    $db->prepare("UPDATE orders SET payment_status = 'verified' WHERE id = ?")->execute([$order_id]);
                }
                
                $db->commit();
                $message = "Status pesanan #" . str_pad($order_id, 5, '0', STR_PAD_LEFT) . " berhasil diperbarui menjadi '" . $new_status . "'.";
            } catch (Exception $e) {
                $db->rollBack();
                $error = $e->getMessage();
            }
        }
    }
}

// 2. DETAIL PESANAN SPESIFIK (jika di-click)
$detail_order = null;
$detail_items = [];
if (isset($_GET['id'])) {
    $detail_id = intval($_GET['id']);
    
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$detail_id]);
    $detail_order = $stmt->fetch();
    
    if ($detail_order) {
        $items_stmt = $db->prepare("
            SELECT oi.*, p.name as product_name 
            FROM order_items oi
            JOIN products p ON oi.product_id = p.id
            WHERE oi.order_id = ?
        ");
        $items_stmt->execute([$detail_id]);
        $detail_items = $items_stmt->fetchAll();
    }
}

// 3. DAFTAR SEMUA PESANAN
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
if (!empty($search_query)) {
    $list_stmt = $db->prepare("SELECT * FROM orders WHERE customer_name LIKE ? OR id LIKE ? ORDER BY id DESC");
    $list_stmt->execute(["%$search_query%", "%$search_query%"]);
    $orders = $list_stmt->fetchAll();
} else {
    $orders = $db->query("SELECT * FROM orders ORDER BY id DESC")->fetchAll();
}
?>

<?php if (!empty($message)): ?>
    <div class="alert-box alert-success">
        <i class="fa-solid fa-circle-check"></i> <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if (!empty($error)): ?>
    <div class="alert-box alert-danger">
        <i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<div style="display: grid; grid-template-columns: <?php echo $detail_order ? '1.15fr 1fr' : '1fr'; ?>; gap: 2rem; align-items: start;">
    
    <!-- Bagian 1: Daftar Pesanan -->
    <div class="panel">
        <div class="panel-header">
            <h2 class="panel-title"><i class="fa-solid fa-list-check"></i> Daftar Semua Pesanan</h2>
            
            <form action="orders.php" method="GET" style="display: flex; gap: 0.5rem; max-width: 300px;">
                <input type="text" name="search" class="form-control" placeholder="Cari nama / Invoice ID..." value="<?php echo htmlspecialchars($search_query); ?>" style="padding: 0.4rem 0.8rem; font-size: 0.85rem;">
                <button type="submit" class="btn-admin btn-admin-outline" style="padding: 0.4rem 0.8rem; font-size: 0.85rem;"><i class="fa-solid fa-magnifying-glass"></i></button>
            </form>
        </div>

        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Invoice</th>
                        <th>Pelanggan</th>
                        <th>Tanggal</th>
                        <th>Total</th>
                        <th>Bukti Transfer</th>
                        <th>Status Pesanan</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($orders) > 0): ?>
                        <?php foreach ($orders as $ord): ?>
                            <?php $p_status = isset($ord['payment_status']) ? $ord['payment_status'] : 'unverified'; ?>
                            <tr class="<?php echo $detail_order && $detail_order['id'] == $ord['id'] ? 'active-row' : ''; ?>" style="<?php echo $detail_order && $detail_order['id'] == $ord['id'] ? 'background-color: #FAF4F2;' : ''; ?>">
                                <td style="font-family: monospace; font-weight: bold;">
                                    INV-<?php echo str_pad($ord['id'], 6, '0', STR_PAD_LEFT); ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($ord['customer_name']); ?></strong>
                                    <div style="font-size: 0.8rem; color: var(--text-muted);"><?php echo htmlspecialchars($ord['customer_phone']); ?></div>
                                </td>
                                <td><?php echo date('d/m/Y H:i', strtotime($ord['created_at'])); ?></td>
                                <td style="font-weight: 600;">Rp <?php echo number_format($ord['total_price'], 0, ',', '.'); ?></td>
                                <td>
                                    <?php if (!empty($ord['payment_proof'])): ?>
                                        <div style="display: flex; align-items: center; gap: 0.4rem;">
                                            <a href="../<?php echo htmlspecialchars($ord['payment_proof']); ?>" target="_blank" title="Klik untuk lihat gambar bukti transfer">
                                                <img src="../<?php echo htmlspecialchars($ord['payment_proof']); ?>" alt="Bukti" style="width: 38px; height: 38px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color);">
                                            </a>
                                            <div>
                                                <?php if ($p_status === 'verified'): ?>
                                                    <span class="badge badge-completed" style="font-size: 0.75rem;"><i class="fa-solid fa-check"></i> Diverifikasi</span>
                                                <?php elseif ($p_status === 'rejected'): ?>
                                                    <span class="badge badge-cancelled" style="font-size: 0.75rem;"><i class="fa-solid fa-xmark"></i> Ditolak</span>
                                                <?php else: ?>
                                                    <span class="badge" style="background-color: rgba(197, 137, 64, 0.15); color: #B36B00; font-size: 0.75rem; font-weight: 700;">
                                                        <i class="fa-solid fa-bell"></i> Perlu Verifikasi
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <span style="font-size: 0.8rem; color: #9E9E9E; font-style: italic;">
                                            <i class="fa-regular fa-circle-question"></i> Belum Unggah
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-<?php echo $ord['status']; ?>">
                                        <?php 
                                        $labels = ['pending'=>'Menunggu', 'processing'=>'Diproses', 'completed'=>'Selesai', 'cancelled'=>'Dibatalkan'];
                                        echo isset($labels[$ord['status']]) ? $labels[$ord['status']] : $ord['status'];
                                        ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="orders.php?id=<?php echo $ord['id']; ?><?php echo !empty($search_query) ? '&search='.urlencode($search_query) : ''; ?>" class="btn-admin btn-admin-primary" style="padding: 0.3rem 0.6rem; font-size: 0.8rem;">
                                        <i class="fa-solid fa-magnifying-glass"></i> Detail / Verifikasi
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; color: var(--text-muted); padding: 3rem;">Tidak ada pesanan yang sesuai pencarian.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Bagian 2: Tampilan Detail & Verifikasi Pesanan -->
    <?php if ($detail_order): ?>
        <?php $p_status = isset($detail_order['payment_status']) ? $detail_order['payment_status'] : 'unverified'; ?>
        <div class="panel" style="border-left: 4px solid var(--accent);">
            <div class="panel-header" style="border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1.2rem;">
                <h2 class="panel-title"><i class="fa-solid fa-receipt"></i> Invoice INV-<?php echo str_pad($detail_order['id'], 6, '0', STR_PAD_LEFT); ?></h2>
                <a href="orders.php" style="color: var(--text-muted); font-size: 0.85rem;"><i class="fa-solid fa-circle-xmark"></i> Tutup</a>
            </div>

            <div style="font-size: 0.9rem; margin-bottom: 1.5rem; display: grid; grid-template-columns: 1fr 1.8fr; gap: 0.6rem;">
                <span style="color: var(--text-muted);">Pelanggan:</span>
                <strong><?php echo htmlspecialchars($detail_order['customer_name']); ?></strong>
                
                <span style="color: var(--text-muted);">No. Telepon:</span>
                <strong><?php echo htmlspecialchars($detail_order['customer_phone']); ?></strong>
                
                <span style="color: var(--text-muted);">Alamat Kirim:</span>
                <span><?php echo nl2br(htmlspecialchars($detail_order['customer_address'])); ?></span>
                
                <span style="color: var(--text-muted);">Tanggal Order:</span>
                <span><?php echo date('d F Y, H:i', strtotime($detail_order['created_at'])); ?> WIB</span>

                <span style="color: var(--text-muted);">Metode Bayar:</span>
                <strong style="color: var(--primary-color);"><?php echo htmlspecialchars($detail_order['payment_method']); ?></strong>
            </div>

            <!-- KOTAK VERIFIKASI BUKTI TRANSFER -->
            <div style="background: #FAF8F5; border: 1px solid var(--border-color); border-radius: 8px; padding: 1.2rem; margin-bottom: 1.5rem; border-top: 3px solid var(--accent);">
                <h4 style="font-size: 0.95rem; margin-bottom: 0.8rem; color: var(--text-dark); display: flex; align-items: center; justify-content: space-between;">
                    <span><i class="fa-solid fa-file-invoice-dollar" style="color: var(--accent);"></i> Bukti Transfer Pembayaran</span>
                    <?php if ($p_status === 'verified'): ?>
                        <span class="badge badge-completed"><i class="fa-solid fa-circle-check"></i> Terverifikasi</span>
                    <?php elseif ($p_status === 'rejected'): ?>
                        <span class="badge badge-cancelled"><i class="fa-solid fa-circle-xmark"></i> Ditolak</span>
                    <?php else: ?>
                        <span class="badge badge-pending"><i class="fa-solid fa-clock"></i> Belum Diverifikasi</span>
                    <?php endif; ?>
                </h4>

                <?php if (!empty($detail_order['payment_proof'])): ?>
                    <div style="text-align: center; margin-bottom: 1rem; background: white; padding: 0.5rem; border-radius: 6px; border: 1px solid var(--border-color);">
                        <a href="../<?php echo htmlspecialchars($detail_order['payment_proof']); ?>" target="_blank">
                            <img src="../<?php echo htmlspecialchars($detail_order['payment_proof']); ?>" alt="Bukti Transfer" style="max-width: 100%; max-height: 250px; object-fit: contain; border-radius: 4px; display: block; margin: 0 auto;">
                        </a>
                        <small style="color: var(--text-muted); display: block; margin-top: 0.4rem;">
                            <i class="fa-solid fa-up-right-from-square"></i> Klik gambar untuk melihat ukuran penuh
                        </small>
                    </div>

                    <!-- Tombol Aksi Verifikasi -->
                    <div style="display: flex; gap: 0.6rem;">
                        <form action="orders.php?id=<?php echo $detail_order['id']; ?>" method="POST" style="flex: 1; margin: 0;">
                            <input type="hidden" name="action" value="verify_payment">
                            <input type="hidden" name="order_id" value="<?php echo $detail_order['id']; ?>">
                            <input type="hidden" name="payment_status" value="verified">
                            <button type="submit" class="btn-admin btn-admin-success" style="width: 100%; justify-content: center; font-size: 0.85rem; padding: 0.5rem;">
                                <i class="fa-solid fa-circle-check"></i> Setujui / Verifikasi
                            </button>
                        </form>

                        <form action="orders.php?id=<?php echo $detail_order['id']; ?>" method="POST" style="flex: 1; margin: 0;">
                            <input type="hidden" name="action" value="verify_payment">
                            <input type="hidden" name="order_id" value="<?php echo $detail_order['id']; ?>">
                            <input type="hidden" name="payment_status" value="rejected">
                            <button type="submit" class="btn-admin btn-admin-danger" style="width: 100%; justify-content: center; font-size: 0.85rem; padding: 0.5rem;" onclick="return confirm('Apakah Anda yakin ingin menolak bukti transfer ini?')">
                                <i class="fa-solid fa-circle-xmark"></i> Tolak Bukti
                            </button>
                        </form>
                    </div>
                <?php else: ?>
                    <div style="text-align: center; padding: 1.5rem; color: var(--text-muted); background: white; border-radius: 6px; border: 1px dashed var(--border-color);">
                        <i class="fa-regular fa-image" style="font-size: 2rem; margin-bottom: 0.5rem; display: block; opacity: 0.5;"></i>
                        <p style="font-size: 0.85rem;">Pelanggan belum mengunggah foto bukti transfer untuk pesanan ini.</p>
                    </div>
                <?php endif; ?>
            </div>

            <h4 style="font-size: 0.95rem; margin-bottom: 0.8rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.4rem;">Menu Kue yang Dipesan:</h4>
            <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem; margin-bottom: 1.5rem;">
                <thead>
                    <tr style="text-align: left; background-color: #FAF8F5;">
                        <th style="padding: 0.5rem;">Nama Kue</th>
                        <th style="padding: 0.5rem; text-align: center;">Qty</th>
                        <th style="padding: 0.5rem; text-align: right;">Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($detail_items as $item): ?>
                        <tr style="border-bottom: 1px solid var(--border-color);">
                            <td style="padding: 0.6rem;"><?php echo htmlspecialchars($item['product_name']); ?></td>
                            <td style="padding: 0.6rem; text-align: center;"><?php echo $item['quantity']; ?> pcs</td>
                            <td style="padding: 0.6rem; text-align: right;">Rp <?php echo number_format($item['price_at_purchase'] * $item['quantity'], 0, ',', '.'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr style="font-weight: bold; font-size: 0.95rem;">
                        <td colspan="2" style="padding: 0.8rem 0.6rem;">Total Bayar:</td>
                        <td style="padding: 0.8rem 0.6rem; text-align: right; color: var(--text-dark);">Rp <?php echo number_format($detail_order['total_price'], 0, ',', '.'); ?></td>
                    </tr>
                </tbody>
            </table>

            <!-- Form Update Status Pesanan -->
            <form action="orders.php?id=<?php echo $detail_order['id']; ?>" method="POST" class="panel" style="background-color: var(--admin-bg-light); margin-bottom: 0; padding: 1.2rem; border-color: #D7CCC8;">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="order_id" value="<?php echo $detail_order['id']; ?>">
                
                <div class="form-group">
                    <label for="status">Ubah Status Transaksi Pesanan</label>
                    <select name="status" id="status" class="form-control" style="padding: 0.5rem;">
                        <option value="pending" <?php echo $detail_order['status'] === 'pending' ? 'selected' : ''; ?>>Menunggu Konfirmasi (Pending)</option>
                        <option value="processing" <?php echo $detail_order['status'] === 'processing' ? 'selected' : ''; ?>>Sedang Diproses (Processing)</option>
                        <option value="completed" <?php echo $detail_order['status'] === 'completed' ? 'selected' : ''; ?>>Selesai & Dikirim (Completed)</option>
                        <option value="cancelled" <?php echo $detail_order['status'] === 'cancelled' ? 'selected' : ''; ?>>Dibatalkan (Cancelled)</option>
                    </select>
                </div>

                <button type="submit" class="btn-admin btn-admin-primary" style="width: 100%; justify-content: center; font-size: 0.85rem; padding: 0.6rem;">
                    <i class="fa-solid fa-floppy-disk"></i> Simpan Status Baru Pesanan
                </button>
            </form>
        </div>
    <?php endif; ?>

</div>

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