<?php
// admin_panel/pages/order_details.php
// Compatible: PHP 7.x and PHP 8.x
//
// Wallet credit/debit is handled by MySQL triggers ONLY.
// PHP just writes the status — triggers fire automatically.
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

// ── Fetch order ───────────────────────────────────────────────────────────────
$id = $_GET['id'] ?? null;
if (!$id) {
    setFlash('danger', 'No order ID provided.');
    header('Location: orders.php');
    exit;
}

$stmt = $pdo->prepare("
    SELECT o.*, u.reseller_name, u.shop_name, u.email, u.phone AS reseller_phone
    FROM orders o
    LEFT JOIN users u ON o.user_id = u.id
    WHERE o.id = :id
");
$stmt->execute([':id' => $id]);
$order = $stmt->fetch();

if (!$order) {
    setFlash('danger', 'Order not found.');
    header('Location: orders.php');
    exit;
}

$itemsStmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = :oid");
$itemsStmt->execute([':oid' => $id]);
$items = $itemsStmt->fetchAll();

$statuses       = ['pending','confirmed','packaging','shipping','delivered',
                   'partial_delivery','returned','paid_return','cancelled','lost'];
$returnStatuses = ['returned', 'paid_return'];

// ── Handle POST — just write status, trigger does wallet work ─────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $newStatus       = $_POST['status']           ?? $order['status'];
    $courierService  = trim($_POST['courier_service']  ?? $order['courier_service']  ?? '');
    $courierTracking = trim($_POST['courier_tracking'] ?? $order['courier_tracking'] ?? '');
    $adminNote       = trim($_POST['note']             ?? $order['note']             ?? '');

    // Single UPDATE — MySQL triggers (after_order_delivered, after_order_returned)
    // fire automatically and handle all wallet credit/debit logic.
    try {
        $pdo->prepare("
            UPDATE orders
            SET status           = :status,
                courier_service  = :cs,
                courier_tracking = :ct,
                note             = :note
            WHERE id             = :id
        ")->execute([
            ':status' => $newStatus,
            ':cs'     => $courierService  ?: null,
            ':ct'     => $courierTracking ?: null,
            ':note'   => $adminNote,
            ':id'     => $id,
        ]);

        setFlash('success', 'Order updated successfully.');
    } catch (Exception $e) {
        error_log('[order_details POST] id=' . $id . ' | ' . $e->getMessage());
        setFlash('danger', 'Update failed. Please try again.');
    }

    // Refresh
    $stmt->execute([':id' => $id]);
    $order = $stmt->fetch();
    $itemsStmt->execute([':oid' => $id]);
    $items = $itemsStmt->fetchAll();
}

// ── Render ────────────────────────────────────────────────────────────────────
require_once '../includes/header.php';

$sellingSubtotal     = (float)$order['total_selling'];
$buyingSubtotal      = (float)$order['total_buying'];
$courierFee          = (float)$order['courier_fee'];
$packagingFee        = (float)$order['packaging_fee'];
$totalCost           = $buyingSubtotal + $courierFee + $packagingFee;
$collectFromCustomer = $sellingSubtotal + $courierFee;
$profit              = $collectFromCustomer - $totalCost;
$isReturn            = in_array($order['status'], $returnStatuses);

// Wallet audit trail for this order
$walletStmt = $pdo->prepare("
    SELECT type, amount, balance_after, description, created_at
    FROM wallet_transactions
    WHERE order_id = ?
    ORDER BY id ASC
");
$walletStmt->execute([$id]);
$walletTxns = $walletStmt->fetchAll();

// Build return breakdown — PHP 7 compatible (strpos, not str_contains)
$totalDebited     = 0.0;
$courierDebited   = 0.0;
$packagingDebited = 0.0;
$profitDebited    = 0.0;
foreach ($walletTxns as $t) {
    if ($t['type'] === 'debit') {
        $totalDebited += (float)$t['amount'];
        if (strpos($t['description'], '[RETURN-COURIER]')   !== false) $courierDebited   = (float)$t['amount'];
        if (strpos($t['description'], '[RETURN-PACKAGING]') !== false) $packagingDebited = (float)$t['amount'];
        if (strpos($t['description'], '[RETURN-PROFIT]')    !== false) $profitDebited    = (float)$t['amount'];
        if (strpos($t['description'], 'Profit reversed')    !== false) $profitDebited    = (float)$t['amount'];
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h1 class="h2">Order #<?= htmlspecialchars($order['order_number']) ?></h1>
    <a href="orders.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Orders</a>
</div>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">

    <!-- Left column -->
    <div class="col-md-4">

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Customer Info</h5></div>
            <div class="card-body">
                <p><strong>Name:</strong> <?= htmlspecialchars($order['customer_name'] ?? 'N/A') ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($order['customer_phone'] ?? 'N/A') ?></p>
                <p><strong>Address:</strong><br><?= nl2br(htmlspecialchars($order['customer_address'] ?? '')) ?></p>
                <?php if (!empty($order['district'])): ?><p><strong>District:</strong> <?= htmlspecialchars($order['district']) ?></p><?php endif; ?>
                <?php if (!empty($order['upazila'])): ?><p><strong>Upazila:</strong> <?= htmlspecialchars($order['upazila']) ?></p><?php endif; ?>
                <p><strong>Inside Dhaka:</strong> <?= $order['inside_dhaka'] ? 'Yes' : 'No' ?></p>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Reseller Info</h5></div>
            <div class="card-body">
                <p><strong>Name:</strong>  <?= htmlspecialchars($order['reseller_name']  ?? 'N/A') ?></p>
                <p><strong>Shop:</strong>  <?= htmlspecialchars($order['shop_name']       ?? 'N/A') ?></p>
                <p><strong>Email:</strong> <?= htmlspecialchars($order['email']           ?? '') ?></p>
                <p><strong>Phone:</strong> <?= htmlspecialchars($order['reseller_phone']  ?? '') ?></p>
            </div>
        </div>

        <?php if (!empty($walletTxns)): ?>
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Wallet Activity</h5></div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="table-light">
                        <tr><th>Type</th><th>Amount</th><th>Balance After</th><th>Description</th><th>Date</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($walletTxns as $t): ?>
                        <tr>
                            <td><?= $t['type'] === 'credit'
                                ? '<span class="badge bg-success">Credit</span>'
                                : '<span class="badge bg-danger">Debit</span>' ?></td>
                            <td>Tk.<?= number_format((float)$t['amount'], 2) ?></td>
                            <td class="<?= (float)$t['balance_after'] < 0 ? 'text-danger fw-bold' : '' ?>">
                                Tk.<?= number_format((float)$t['balance_after'], 2) ?>
                                <?php if ((float)$t['balance_after'] < 0): ?>
                                    <span class="badge bg-danger ms-1">Negative</span>
                                <?php endif; ?>
                            </td>
                            <td style="font-size:10px"><?= htmlspecialchars($t['description']) ?></td>
                            <td style="font-size:11px"><?= date('d M y, H:i', strtotime($t['created_at'])) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($isReturn && ($courierDebited > 0 || $packagingDebited > 0 || $profitDebited > 0)): ?>
        <div class="card shadow-sm mb-4 border-danger">
            <div class="card-header bg-danger text-white"><h5 class="mb-0">Return Deductions</h5></div>
            <div class="card-body">
                <?php if ($courierDebited > 0): ?>
                <div class="d-flex justify-content-between mb-1">
                    <span>Courier Fee <span class="badge bg-danger">Always charged</span></span>
                    <strong class="text-danger">-Tk.<?= number_format($courierDebited, 2) ?></strong>
                </div>
                <?php endif; ?>
                <?php if ($packagingDebited > 0): ?>
                <div class="d-flex justify-content-between mb-1">
                    <span>Packaging Fee <span class="badge bg-danger">Always charged</span></span>
                    <strong class="text-danger">-Tk.<?= number_format($packagingDebited, 2) ?></strong>
                </div>
                <?php endif; ?>
                <?php if ($profitDebited > 0): ?>
                <div class="d-flex justify-content-between mb-1">
                    <span>Profit Reversed <span class="badge bg-warning text-dark">If balance sufficient</span></span>
                    <strong class="text-danger">-Tk.<?= number_format($profitDebited, 2) ?></strong>
                </div>
                <?php elseif ($profit > 0): ?>
                <div class="d-flex justify-content-between mb-1 text-muted">
                    <span>Profit Reversal <span class="badge bg-secondary">Skipped — insufficient balance</span></span>
                    <span>Tk.<?= number_format($profit, 2) ?></span>
                </div>
                <?php endif; ?>
                <hr class="my-2">
                <div class="d-flex justify-content-between fw-bold">
                    <span>Total Deducted</span>
                    <span class="text-danger">-Tk.<?= number_format($totalDebited, 2) ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <!-- Right column -->
    <div class="col-md-8">

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Order Items</h5></div>
            <div class="card-body p-0">
                <table class="table table-striped mb-0">
                    <thead>
                        <tr><th>Product</th><th>Buying</th><th>Selling</th><th>Qty</th><th>Profit</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $item): ?>
                        <tr>
                            <td><?= htmlspecialchars($item['product_name']) ?></td>
                            <td>Tk.<?= number_format((float)$item['buying_price'], 2) ?></td>
                            <td>Tk.<?= number_format((float)$item['reseller_price'], 2) ?></td>
                            <td><?= (int)$item['quantity'] ?></td>
                            <td>Tk.<?= number_format($profit, 2) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card shadow-sm mb-4 bg-dark text-white">
            <div class="card-header bg-dark border-secondary"><h5 class="mb-0 text-white">Order Summary</h5></div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-2"><span>Selling Subtotal</span><strong>Tk. <?= number_format($sellingSubtotal, 2) ?></strong></div>
                <div class="d-flex justify-content-between mb-2"><span>Buying Subtotal</span><strong>Tk. <?= number_format($buyingSubtotal, 2) ?></strong></div>
                <div class="d-flex justify-content-between mb-2"><span>Courier Fee</span><strong>Tk. <?= number_format($courierFee, 2) ?></strong></div>
                <div class="d-flex justify-content-between mb-2"><span>Packaging Fee</span><strong>Tk. <?= number_format($packagingFee, 2) ?></strong></div>
                <hr class="border-secondary">
                <div class="d-flex justify-content-between mb-2"><span>Total Cost (You Pay)</span><strong>Tk. <?= number_format($totalCost, 2) ?></strong></div>
                <div class="d-flex justify-content-between mb-2"><span>Collect from Customer</span><strong>Tk. <?= number_format($collectFromCustomer, 2) ?></strong></div>
                <hr class="border-secondary">
                <div class="d-flex justify-content-between">
                    <span>
                        Your Profit
                        <?php if ($isReturn): ?>
                            <span class="badge bg-danger ms-1">RETURNED</span>
                        <?php elseif ($order['status'] === 'delivered'): ?>
                            <span class="badge bg-success ms-1">CREDITED</span>
                        <?php endif; ?>
                    </span>
                    <strong class="<?= $isReturn ? 'text-danger' : 'text-success' ?>">
                        <?= $isReturn ? '-' : '' ?>Tk. <?= number_format($profit, 2) ?>
                    </strong>
                </div>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white"><h5 class="mb-0">Payment & Courier</h5></div>
            <div class="card-body">
                <p><strong>Payment Method:</strong> <?= htmlspecialchars($order['payment_method']) ?></p>
                <?php if (!empty($order['payment_ref'])): ?><p><strong>Payment Ref:</strong> <?= htmlspecialchars($order['payment_ref']) ?></p><?php endif; ?>
                <p><strong>Courier Service:</strong> <?= htmlspecialchars($order['courier_service'] ?? 'Not set') ?></p>
                <?php if (!empty($order['courier_tracking'])): ?><p><strong>Tracking Number:</strong> <?= htmlspecialchars($order['courier_tracking']) ?></p><?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white d-flex align-items-center gap-2">
                <h5 class="mb-0">Update Order</h5>
                <?php if ($isReturn): ?>
                    <span class="badge bg-danger">Return charges applied to wallet</span>
                <?php elseif ($order['status'] === 'delivered'): ?>
                    <span class="badge bg-success">Profit credited to wallet</span>
                <?php endif; ?>
            </div>
            <div class="card-body">

                <?php if ($isReturn && $totalDebited > 0): ?>
                <div class="alert alert-warning py-2 mb-3">
                    <i class="bi bi-exclamation-triangle me-1"></i>
                    <strong>Return charges applied:</strong>
                    <ul class="mb-0 mt-1" style="font-size:13px">
                        <?php if ($courierDebited > 0): ?><li>Tk.<?= number_format($courierDebited, 2) ?> courier fee deducted</li><?php endif; ?>
                        <?php if ($packagingDebited > 0): ?><li>Tk.<?= number_format($packagingDebited, 2) ?> packaging fee deducted</li><?php endif; ?>
                        <?php if ($profitDebited > 0): ?>
                            <li>Tk.<?= number_format($profitDebited, 2) ?> profit reversed</li>
                        <?php elseif ($profit > 0): ?>
                            <li class="text-muted">Profit not reversed (insufficient balance at time of return)</li>
                        <?php endif; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <?php foreach ($statuses as $s): ?>
                                    <option value="<?= $s ?>" <?= $order['status'] === $s ? 'selected' : '' ?>>
                                        <?= ucfirst(str_replace('_', ' ', $s)) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Courier Service</label>
                            <input type="text" name="courier_service" class="form-control"
                                   placeholder="steadfast / pathao / redx"
                                   value="<?= htmlspecialchars($order['courier_service'] ?? '') ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Tracking Number</label>
                            <input type="text" name="courier_tracking" class="form-control"
                                   placeholder="Enter tracking code"
                                   value="<?= htmlspecialchars($order['courier_tracking'] ?? '') ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Admin Note</label>
                            <input type="text" name="note" class="form-control"
                                   placeholder="Internal note"
                                   value="<?= htmlspecialchars($order['note'] ?? '') ?>">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Update Order
                    </button>
                </form>
            </div>
        </div>

    </div>
</div>

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