<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/email.php';
require_once __DIR__ . '/../app/helpers/activity.php';


require_admin();

$pageTitle = 'Orders';
$success = '';
$error = '';

if (isset($_GET['updated'])) {
    $success = 'Order updated successfully.';
}

$orderId = isset($_GET['view']) ? (int) $_GET['view'] : 0;

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $updateOrderId = (int) ($_POST['order_id'] ?? 0);
        $paymentStatus = $_POST['payment_status'] ?? 'pending';
        $orderStatus = $_POST['order_status'] ?? 'pending';
        $shippingStatus = $_POST['shipping_status'] ?? 'not_shipped';
        $trackingNumber = trim($_POST['tracking_number'] ?? '');

        $allowedPayment = ['pending', 'paid', 'failed', 'refunded', 'cancelled'];
        $allowedOrder = ['pending', 'processing', 'shipped', 'completed', 'cancelled', 'refunded'];
        $allowedShipping = ['not_shipped', 'packed', 'shipped', 'delivered'];

        if ($updateOrderId <= 0) {
            $error = 'Invalid order.';
        } elseif (!in_array($paymentStatus, $allowedPayment, true)) {
            $error = 'Invalid payment status.';
        } elseif (!in_array($orderStatus, $allowedOrder, true)) {
            $error = 'Invalid order status.';
        } elseif (!in_array($shippingStatus, $allowedShipping, true)) {
            $error = 'Invalid shipping status.';
        } else {
            try {
                $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? LIMIT 1");
                $stmt->execute([$updateOrderId]);
                $existingOrder = $stmt->fetch();

                if (!$existingOrder) {
                    $error = 'Order not found.';
                } else {
                    $pdo->beginTransaction();

                    $stmt = $pdo->prepare("
                        UPDATE orders
                        SET payment_status = ?,
                            order_status = ?,
                            shipping_status = ?,
                            tracking_number = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $paymentStatus,
                        $orderStatus,
                        $shippingStatus,
                        $trackingNumber !== '' ? $trackingNumber : null,
                        $updateOrderId
                    ]);

                    if (
                        $existingOrder['payment_status'] !== 'paid'
                        && $paymentStatus === 'paid'
                        && !empty($existingOrder['customer_id'])
                    ) {
                        $points = (int) floor((float) $existingOrder['total_amount']);

                        if ($points > 0) {
                            $check = $pdo->prepare("
    SELECT id
    FROM loyalty_transactions
    WHERE customer_id = ?
      AND description = ?
    LIMIT 1
");

                            $loyaltyDescription = 'Points earned from order ' . $existingOrder['order_number'];

                            $check->execute([
                                $existingOrder['customer_id'],
                                $loyaltyDescription
                            ]);

                            if (!$check->fetch()) {
                                $stmt = $pdo->prepare("
                                    SELECT *
                                    FROM customer_loyalty
                                    WHERE customer_id = ?
                                    LIMIT 1
                                ");
                                $stmt->execute([$existingOrder['customer_id']]);
                                $loyalty = $stmt->fetch();

                                if ($loyalty) {
                                    $stmt = $pdo->prepare("
                                        UPDATE customer_loyalty
                                        SET points_balance = points_balance + ?,
                                            lifetime_points = lifetime_points + ?
                                        WHERE customer_id = ?
                                    ");
                                    $stmt->execute([
                                        $points,
                                        $points,
                                        $existingOrder['customer_id']
                                    ]);
                                } else {
                                    $stmt = $pdo->prepare("
                                        INSERT INTO customer_loyalty (
                                            customer_id,
                                            points_balance,
                                            lifetime_points
                                        ) VALUES (?, ?, ?)
                                    ");
                                    $stmt->execute([
                                        $existingOrder['customer_id'],
                                        $points,
                                        $points
                                    ]);
                                }

                                $stmt = $pdo->prepare("
    INSERT INTO loyalty_transactions (
        customer_id,
        transaction_type,
        points,
        description
    ) VALUES (?, 'earn', ?, ?)
");

                                $stmt->execute([
                                    $existingOrder['customer_id'],
                                    $points,
                                    $loyaltyDescription
                                ]);
                            }
                        }
                    }
                    if (
                        $existingOrder['payment_status'] !== 'paid'
                        && $paymentStatus === 'paid'
                        && !empty($existingOrder['customer_id'])
                    ) {
                        $referredCustomerId = (int) $existingOrder['customer_id'];

                        $stmt = $pdo->prepare("
        SELECT *
        FROM referrals
        WHERE referred_customer_id = ?
          AND reward_status = 'pending'
        LIMIT 1
    ");
                        $stmt->execute([$referredCustomerId]);
                        $pendingReferral = $stmt->fetch();

                        if ($pendingReferral) {
                            $stmt = $pdo->prepare("
            SELECT *
            FROM referral_rewards
            WHERE referral_id = ?
              AND status = 'pending'
            LIMIT 1
        ");
                            $stmt->execute([$pendingReferral['id']]);
                            $pendingReward = $stmt->fetch();

                            if ($pendingReward && $pendingReward['reward_type'] === 'points') {
                                $rewardPoints = (int) $pendingReward['reward_value'];
                                $referrerCustomerId = (int) $pendingReferral['referrer_customer_id'];

                                $stmt = $pdo->prepare("
                SELECT id
                FROM customer_loyalty
                WHERE customer_id = ?
                LIMIT 1
            ");
                                $stmt->execute([$referrerCustomerId]);
                                $referrerLoyalty = $stmt->fetch();

                                if ($referrerLoyalty) {
                                    $stmt = $pdo->prepare("
                    UPDATE customer_loyalty
                    SET points_balance = points_balance + ?,
                        lifetime_points = lifetime_points + ?
                    WHERE customer_id = ?
                ");
                                    $stmt->execute([
                                        $rewardPoints,
                                        $rewardPoints,
                                        $referrerCustomerId
                                    ]);
                                } else {
                                    $stmt = $pdo->prepare("
                    INSERT INTO customer_loyalty (
                        customer_id,
                        points_balance,
                        lifetime_points
                    ) VALUES (?, ?, ?)
                ");
                                    $stmt->execute([
                                        $referrerCustomerId,
                                        $rewardPoints,
                                        $rewardPoints
                                    ]);
                                }

                                $description = 'Referral reward earned from referred customer order ' . $existingOrder['order_number'];

                                $stmt = $pdo->prepare("
                INSERT INTO loyalty_transactions (
                    customer_id,
                    order_id,
                    transaction_type,
                    points,
                    description
                ) VALUES (?, ?, 'earn', ?, ?)
            ");
                                $stmt->execute([
                                    $referrerCustomerId,
                                    $existingOrder['id'],
                                    $rewardPoints,
                                    $description
                                ]);

                                $stmt = $pdo->prepare("
                UPDATE referral_rewards
                SET status = 'issued',
                    issued_at = NOW()
                WHERE id = ?
            ");
                                $stmt->execute([$pendingReward['id']]);

                                $stmt = $pdo->prepare("
                UPDATE referrals
                SET reward_status = 'paid'
                WHERE id = ?
            ");
                                $stmt->execute([$pendingReferral['id']]);
                                $stmt = $pdo->prepare("
    SELECT first_name, last_name, email
    FROM customers
    WHERE id = ?
    LIMIT 1
");
                                $stmt->execute([$referrerCustomerId]);
                                $referrerCustomer = $stmt->fetch();

                                if ($referrerCustomer) {
                                    $siteName = function_exists('get_setting') ? get_setting('site_name', APP_NAME) : APP_NAME;

                                    $referrerName = trim($referrerCustomer['first_name'] . ' ' . $referrerCustomer['last_name']);

                                    queue_template_email(
                                        'referral_reward_issued',
                                        $referrerCustomer['email'],
                                        [
                                            'site_name' => $siteName,
                                            'customer_name' => $referrerName !== '' ? $referrerName : 'Customer',
                                            'order_number' => $existingOrder['order_number'],
                                            'order_total' => format_price($existingOrder['total_amount'], $existingOrder['currency_code']),
                                            'payment_status' => ucfirst($paymentStatus),
                                            'points' => (string) $rewardPoints
                                        ],
                                        $referrerCustomerId,
                                        $existingOrder['id']
                                    );
                                }
                            }
                        }
                    }
                    if ($existingOrder['payment_status'] !== $paymentStatus) {
                        $siteName = function_exists('get_setting') ? get_setting('site_name', APP_NAME) : APP_NAME;

                        queue_template_email(
                            'payment_status_update',
                            $existingOrder['customer_email'],
                            [
                                'site_name' => $siteName,
                                'customer_name' => 'Customer',
                                'order_number' => $existingOrder['order_number'],
                                'order_total' => format_price($existingOrder['total_amount'], $existingOrder['currency_code']),
                                'payment_status' => ucfirst($paymentStatus),
                                'points' => '0'
                            ],
                            $existingOrder['customer_id'] ?? null,
                            $existingOrder['id']
                        );
                    }
                    log_admin_activity(
                        'order_updated',
                        'Order updated: ' . $existingOrder['order_number'] .
                            ' | Payment: ' . $existingOrder['payment_status'] . ' → ' . $paymentStatus .
                            ' | Order: ' . $existingOrder['order_status'] . ' → ' . $orderStatus .
                            ' | Shipping: ' . $existingOrder['shipping_status'] . ' → ' . $shippingStatus
                    );
                    $pdo->commit();

                    redirect(ADMIN_URL . '/orders.php?view=' . $updateOrderId . '&updated=1');
                }
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                $error = 'Order could not be updated: ' . $e->getMessage();
            }
        }
    }
}

if ($orderId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? LIMIT 1");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();

    if (!$order) {
        redirect(ADMIN_URL . '/orders.php');
    }

    $stmt = $pdo->prepare("
    SELECT 
        oi.*,
        p.slug,
        p.product_name AS current_product_name,
        p.sku AS product_sku,
        (
            SELECT image_path
            FROM product_images
            WHERE product_id = p.id
            ORDER BY is_primary DESC, sort_order ASC, id ASC
            LIMIT 1
        ) AS product_image,
        pv.variation_value,
        pv.variation_name AS current_variation_name,
        pv.sku AS variation_sku,
        pv.image_path AS variation_image,
        pv.color_code
    FROM order_items oi
    LEFT JOIN products p ON oi.product_id = p.id
    LEFT JOIN product_variations pv ON oi.variation_id = pv.id
    WHERE oi.order_id = ?
    ORDER BY oi.id ASC
");
    $stmt->execute([$orderId]);
    $orderItems = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT * FROM payments WHERE order_id = ? ORDER BY id DESC");
    $stmt->execute([$orderId]);
    $payments = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT * FROM gift_orders WHERE order_id = ? LIMIT 1");
    $stmt->execute([$orderId]);
    $giftOrder = $stmt->fetch();

    require_once __DIR__ . '/includes/header.php';
    require_once __DIR__ . '/includes/sidebar.php';
?>

    <main class="admin-main">
        <div class="admin-topbar">
            <div>
                <h1>Order <?= e($order['order_number']); ?></h1>
                <div class="admin-user">Placed on <?= e(date('d M Y, h:i A', strtotime($order['created_at']))); ?></div>
            </div>

            <a href="<?= e(ADMIN_URL); ?>/orders.php" class="admin-btn admin-btn-light">Back to Orders</a>
        </div>

        <?php if ($success): ?>
            <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
        <?php endif; ?>

        <div class="admin-order-detail-layout">
            <div>
                <section class="admin-panel admin-order-items-panel">
                    <div class="admin-panel-head">
                        <div>
                            <h2>Order Items</h2>
                            <p>Use this packing view to confirm product, variation, SKU, quantity, and price.</p>
                        </div>

                        <span class="admin-status-pill">
                            <?= e(count($orderItems)); ?> item<?= count($orderItems) === 1 ? '' : 's'; ?>
                        </span>
                    </div>

                    <div class="admin-order-items-list">
                        <?php foreach ($orderItems as $item): ?>
                            <?php
                            $displayImage = $item['variation_image'] ?: ($item['product_image'] ?? '');
                            $displaySku = $item['variation_sku'] ?: ($item['sku'] ?: ($item['product_sku'] ?? '-'));
                            $displayVariation = $item['variation_name'] ?: '';

                            if (!$displayVariation && !empty($item['current_variation_name']) && !empty($item['variation_value'])) {
                                $displayVariation = $item['current_variation_name'] . ': ' . $item['variation_value'];
                            }
                            ?>

                            <article class="admin-order-item-card">
                                <div class="admin-order-item-image">
                                    <?php if (!empty($displayImage)): ?>
                                        <img src="<?= e(BASE_URL . '/' . $displayImage); ?>" alt="<?= e($item['product_name']); ?>">
                                    <?php else: ?>
                                        <span><?= e(substr($item['product_name'], 0, 1)); ?></span>
                                    <?php endif; ?>
                                </div>

                                <div class="admin-order-item-info">
                                    <div class="admin-order-item-top">
                                        <div>
                                            <h3>
                                                <?php if (!empty($item['slug'])): ?>
                                                    <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($item['slug']); ?>" target="_blank">
                                                        <?= e($item['product_name']); ?>
                                                    </a>
                                                <?php else: ?>
                                                    <?= e($item['product_name']); ?>
                                                <?php endif; ?>
                                            </h3>

                                            <?php if (!empty($displayVariation)): ?>
                                                <p class="admin-order-variation">
                                                    <?php if (!empty($item['color_code'])): ?>
                                                        <span class="admin-order-color-dot" style="background: <?= e($item['color_code']); ?>;"></span>
                                                    <?php endif; ?>

                                                    <?= e($displayVariation); ?>
                                                </p>
                                            <?php endif; ?>
                                        </div>

                                        <strong class="admin-order-line-total">
                                            <?= e(format_price($item['total_price'], $order['currency_code'])); ?>
                                        </strong>
                                    </div>

                                    <div class="admin-order-item-meta">
                                        <span>
                                            SKU
                                            <strong><?= e($displaySku ?: '-'); ?></strong>
                                        </span>

                                        <span>
                                            Qty
                                            <strong><?= e($item['quantity']); ?></strong>
                                        </span>

                                        <span>
                                            Unit
                                            <strong><?= e(format_price($item['unit_price'], $order['currency_code'])); ?></strong>
                                        </span>

                                        <span>
                                            Packing
                                            <strong><?= !empty($displayVariation) ? 'Check option' : 'Standard item'; ?></strong>
                                        </span>
                                    </div>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </section>

                <section class="admin-panel admin-order-address-panel">
    <h2>Customer & Address Details</h2>

                    <div class="admin-form-grid">
                        <div>
                            <h3>Customer</h3>
                            <p>
                                <strong>Email:</strong> <?= e($order['customer_email']); ?><br>
                                <strong>Phone:</strong> <?= e($order['customer_phone'] ?? '-'); ?>
                            </p>
                        </div>

                        <div>
                            <h3>Tracking</h3>
                            <p>
                                <strong>Tracking Number:</strong> <?= e($order['tracking_number'] ?? '-'); ?><br>
                                <strong>Shipping Status:</strong> <?= e(ucwords(str_replace('_', ' ', $order['shipping_status']))); ?>
                            </p>
                        </div>
                    </div>

                    <div class="admin-form-grid">
                        <div>
                            <h3>Billing Address</h3>
                            <p class="admin-address-text"><?= e($order['billing_address']); ?></p>
                        </div>

                        <div>
                            <h3>Shipping Address</h3>
                            <p class="admin-address-text"><?= e($order['shipping_address']); ?></p>
                        </div>
                    </div>

                    <?php if (!empty($order['order_notes'])): ?>
                        <h3>Order Notes</h3>
                        <p style="color:#555; line-height:1.6;"><?= nl2br(e($order['order_notes'])); ?></p>
                    <?php endif; ?>
                </section>

                <?php if ($giftOrder): ?>
                    <section class="admin-panel" style="margin-bottom:24px;">
                        <h2>Gift Details</h2>

                        <p>
                            <strong>Recipient Name:</strong> <?= e($giftOrder['recipient_name']); ?><br>
                            <strong>Recipient Email:</strong> <?= e($giftOrder['recipient_email'] ?? '-'); ?><br>
                            <strong>Recipient Phone:</strong> <?= e($giftOrder['recipient_phone'] ?? '-'); ?><br>
                            <strong>Hide Price:</strong> <?= $giftOrder['hide_price'] ? 'Yes' : 'No'; ?><br>
                            <strong>Gift Wrap:</strong> <?= $giftOrder['gift_wrap'] ? 'Yes' : 'No'; ?>
                        </p>

                        <?php if (!empty($giftOrder['gift_message'])): ?>
                            <h3>Gift Message</h3>
                            <p style="color:#555; line-height:1.6;"><?= nl2br(e($giftOrder['gift_message'])); ?></p>
                        <?php endif; ?>
                    </section>
                <?php endif; ?>

                <section class="admin-panel">
                    <h2>Payment Records</h2>

                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Gateway</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Reference</th>
                                <th>Date</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if (!$payments): ?>
                                <tr>
                                    <td colspan="5">No payment records.</td>
                                </tr>
                            <?php endif; ?>

                            <?php foreach ($payments as $payment): ?>
                                <tr>
                                    <td><?= e(ucwords(str_replace('_', ' ', $payment['payment_gateway']))); ?></td>
                                    <td><?= e(format_price($payment['amount'], $payment['currency_code'])); ?></td>
                                    <td><?= e(ucfirst($payment['status'])); ?></td>
                                    <td><?= e($payment['payment_reference'] ?? '-'); ?></td>
                                    <td><?= e(date('d M Y', strtotime($payment['created_at']))); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>
            </div>

            <aside class="admin-panel admin-order-update-card">
    <h2>Update Order</h2>

                <form method="POST">
                    <?= csrf_field(); ?>
                    <input type="hidden" name="order_id" value="<?= e($order['id']); ?>">

                    <div class="admin-field">
                        <label>Payment Status</label>
                        <select name="payment_status">
                            <?php foreach (['pending', 'paid', 'failed', 'refunded', 'cancelled'] as $status): ?>
                                <option value="<?= e($status); ?>" <?= $order['payment_status'] === $status ? 'selected' : ''; ?>>
                                    <?= e(ucfirst($status)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="admin-field">
                        <label>Order Status</label>
                        <select name="order_status">
                            <?php foreach (['pending', 'processing', 'shipped', 'completed', 'cancelled', 'refunded'] as $status): ?>
                                <option value="<?= e($status); ?>" <?= $order['order_status'] === $status ? 'selected' : ''; ?>>
                                    <?= e(ucfirst($status)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="admin-field">
                        <label>Shipping Status</label>
                        <select name="shipping_status">
                            <?php foreach (['not_shipped', 'packed', 'shipped', 'delivered'] as $status): ?>
                                <option value="<?= e($status); ?>" <?= $order['shipping_status'] === $status ? 'selected' : ''; ?>>
                                    <?= e(ucwords(str_replace('_', ' ', $status))); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="admin-field">
                        <label>Tracking Number</label>
                        <input type="text" name="tracking_number" value="<?= e($order['tracking_number'] ?? ''); ?>">
                    </div>

                    <button type="submit" class="admin-btn">Update Order</button>
                </form>

                <hr style="border:none; border-top:1px solid #eee8df; margin:24px 0;">

                <h2>Order Summary</h2>

                <div class="admin-order-summary-lines">
    <div>
        <span>Subtotal</span>
        <strong><?= e(format_price($order['subtotal'], $order['currency_code'])); ?></strong>
    </div>

    <div>
        <span>Discount</span>
        <strong><?= e(format_price($order['discount_amount'], $order['currency_code'])); ?></strong>
    </div>

    <div>
        <span>Shipping</span>
        <strong><?= e(format_price($order['shipping_fee'], $order['currency_code'])); ?></strong>
    </div>

    <div class="admin-order-summary-total">
        <span>Total</span>
        <strong><?= e(format_price($order['total_amount'], $order['currency_code'])); ?></strong>
    </div>
</div>
            </aside>
        </div>
    </main>

<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$orders = $pdo->query("
    SELECT *
    FROM orders
    ORDER BY id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Orders</h1>
            <div class="admin-user">View and manage customer orders.</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <section class="admin-panel">
        <h2>All Orders</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Order</th>
                    <th>Customer</th>
                    <th>Total</th>
                    <th>Payment</th>
                    <th>Order Status</th>
                    <th>Shipping</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$orders): ?>
                    <tr>
                        <td colspan="8">No orders yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($orders as $order): ?>
                    <tr>
                        <td>
                            <strong><?= e($order['order_number']); ?></strong>
                            <?= $order['is_gift'] ? '<br><small>Gift Order</small>' : ''; ?>
                        </td>
                        <td>
                            <?= e($order['customer_email']); ?><br>
                            <small><?= e($order['customer_phone'] ?? '-'); ?></small>
                        </td>
                        <td><?= e(format_price($order['total_amount'], $order['currency_code'])); ?></td>
                        <td>
    <span class="admin-status-pill status-<?= e($order['payment_status']); ?>">
        <?= e(ucfirst($order['payment_status'])); ?>
    </span>
</td>

<td>
    <span class="admin-status-pill status-<?= e($order['order_status']); ?>">
        <?= e(ucfirst($order['order_status'])); ?>
    </span>
</td>

<td>
    <span class="admin-status-pill status-<?= e($order['shipping_status']); ?>">
        <?= e(ucwords(str_replace('_', ' ', $order['shipping_status']))); ?>
    </span>
</td>
                        <td><?= e(date('d M Y', strtotime($order['created_at']))); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/orders.php?view=<?= e($order['id']); ?>">View</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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