<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$orderStmt = $pdo->prepare('SELECT o.*, u.name AS customer_name, u.email, u.phone
    FROM orders o
    JOIN users u ON u.id = o.user_id
    WHERE o.id = ? LIMIT 1');
$orderStmt->execute([$id]);
$order = $orderStmt->fetch();

if (!$order) {
    echo '<div class="alert error">Order tidak ditemukan.</div>';
    require_once __DIR__ . '/../includes/footer_admin.php';
    exit;
}

$itemStmt = $pdo->prepare('SELECT oi.qty, oi.price, oi.subtotal, p.name
    FROM order_items oi JOIN products p ON p.id = oi.product_id
    WHERE oi.order_id = ?');
$itemStmt->execute([$id]);
$items = $itemStmt->fetchAll();

$confirmStmt = $pdo->prepare('SELECT * FROM payment_confirmations WHERE order_id = ? ORDER BY created_at DESC LIMIT 1');
$confirmStmt->execute([$id]);
$confirmation = $confirmStmt->fetch();

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_status') {
        $status = $_POST['status'] ?? 'pending';
        $valid = ['pending','paid','packed','shipped','done','canceled'];
        if (!in_array($status, $valid, true)) {
            $errors['status'] = 'Status tidak valid.';
        } else {
            $stmt = $pdo->prepare('UPDATE orders SET status = ? WHERE id = ?');
            $stmt->execute([$status, $id]);
            flash_message('success', 'Status order diperbarui.');
            redirect(base_url('admin/order_manage.php?id=' . $id));
        }
    }

    if ($action === 'verify_payment' && $confirmation) {
        $verdict = $_POST['verdict'] ?? 'pending';
        if (!in_array($verdict, ['verified','rejected'], true)) {
            $errors['verdict'] = 'Status verifikasi tidak valid.';
        } else {
            $stmt = $pdo->prepare('UPDATE payment_confirmations SET status = ? WHERE id = ?');
            $stmt->execute([$verdict, $confirmation['id']]);

            if ($verdict === 'verified') {
                $stmt = $pdo->prepare('UPDATE orders SET status = "paid" WHERE id = ?');
                $stmt->execute([$id]);
            }

            flash_message('success', 'Verifikasi pembayaran diperbarui.');
            redirect(base_url('admin/order_manage.php?id=' . $id));
        }
    }
}
?>

<h2 class="fw-bold mb-4">Kelola Order</h2>

<div class="row g-4">
    <div class="col-lg-6">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold">Detail Order</h5>
                <p>Kode: <strong><?= sanitize($order['code']); ?></strong></p>
                <p>Customer: <?= sanitize($order['customer_name']); ?> (<?= sanitize($order['email']); ?>)</p>
                <p>No HP: <?= sanitize($order['phone']); ?></p>
                <p>Total: <?= format_currency($order['total']); ?></p>
                <p>Status: <strong><?= sanitize($order['status']); ?></strong></p>

                <form method="post" class="mt-3">
                    <input type="hidden" name="action" value="update_status">
                    <label>Ubah Status</label>
                    <select class="form-select" name="status" required>
                        <?php foreach (['pending','paid','packed','shipped','done','canceled'] as $status): ?>
                            <option value="<?= $status; ?>" <?= $order['status'] === $status ? 'selected' : ''; ?>><?= $status; ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($errors['status'])): ?><small class="error"><?= sanitize($errors['status']); ?></small><?php endif; ?>
                    <button class="btn mt-2" type="submit">Simpan Status</button>
                </form>
            </div>
        </div>

        <div class="card shadow-sm mt-4">
            <div class="card-body">
                <h5 class="fw-bold">Verifikasi Pembayaran</h5>
                <?php if (!$confirmation): ?>
                    <p>Belum ada konfirmasi pembayaran.</p>
                <?php else: ?>
                    <p>Jumlah: <?= format_currency($confirmation['amount']); ?></p>
                    <p>Tanggal: <?= sanitize($confirmation['paid_at']); ?></p>
                    <p>Status: <?= sanitize($confirmation['status']); ?></p>
                    <?php if (!empty($confirmation['proof_file'])): ?>
                        <a class="btn btn-sm" href="<?= base_url('uploads/' . sanitize($confirmation['proof_file'])); ?>" target="_blank">Lihat Bukti</a>
                    <?php endif; ?>

                    <form method="post" class="mt-3">
                        <input type="hidden" name="action" value="verify_payment">
                        <label>Verifikasi</label>
                        <select class="form-select" name="verdict" required>
                            <option value="verified">Verified</option>
                            <option value="rejected">Rejected</option>
                        </select>
                        <?php if (!empty($errors['verdict'])): ?><small class="error"><?= sanitize($errors['verdict']); ?></small><?php endif; ?>
                        <button class="btn mt-2" type="submit">Simpan Verifikasi</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold">Item Order</h5>
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Produk</th>
                                <th>Harga</th>
                                <th>Qty</th>
                                <th>Subtotal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?= sanitize($item['name']); ?></td>
                                    <td><?= format_currency($item['price']); ?></td>
                                    <td><?= (int) $item['qty']; ?></td>
                                    <td><?= format_currency($item['subtotal']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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