<?php
require_once 'db.php';
require_once 'notifications.php';

// Ensure driverPhone column exists in orders table (MySQL compatible)
try {
    $stmt = $pdo->query("SHOW COLUMNS FROM orders LIKE 'driverPhone'");
    $cols = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    if (empty($cols)) {
        $pdo->exec("ALTER TABLE orders ADD COLUMN driverPhone VARCHAR(20) DEFAULT ''");
    }
} catch (Exception $e) {
    try {
        $pdo->exec("ALTER TABLE orders ADD COLUMN driverPhone VARCHAR(20) DEFAULT ''");
    } catch (Exception $e2) {
        // Column may already exist
    }
}

// Internal helper for delivery handling: payout + 100 loyalty coins + notifications
function processOrderDelivery($pdo, $orderId) {
    $stmtItems = $pdo->prepare("SELECT oi.name, oi.qty, oi.price, p.vendorEmail FROM order_items oi LEFT JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
    $stmtItems->execute([$orderId]);
    $items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

    $vendorTotals = [];
    $vendorItemNames = [];
    foreach ($items as $item) {
        $vEmail = $item['vendorEmail'];
        if ($vEmail) {
            if (!isset($vendorTotals[$vEmail])) {
                $vendorTotals[$vEmail] = 0;
                $vendorItemNames[$vEmail] = [];
            }
            $vendorTotals[$vEmail] += ($item['qty'] * $item['price']);
            $vendorItemNames[$vEmail][] = $item['qty'] . 'x ' . $item['name'];
        }
    }

    $timeNow = time();
    foreach ($vendorTotals as $vEmail => $amount) {
        // 1. Payout sales amount to vendor wallet
        $pdo->prepare("UPDATE vendors SET wallet_balance = wallet_balance + ? WHERE contactEmail = ?")->execute([$amount, $vEmail]);

        // 2. Award 100 Loyalty Coins to vendor for completed delivery
        $pdo->prepare("UPDATE vendors SET loyalty_coins = loyalty_coins + 100 WHERE contactEmail = ?")->execute([$vEmail]);

        // 3. Log loyalty transaction
        $stmtLoyalty = $pdo->prepare("INSERT INTO loyalty_transactions (vendor_email, amount, type, description, order_id, createdAt) VALUES (?, ?, ?, ?, ?, ?)");
        $stmtLoyalty->execute([
            $vEmail,
            100,
            'earned_delivery',
            "Earned 100 Loyalty Coins for delivering Order $orderId",
            $orderId,
            $timeNow
        ]);

        // 4. Send in-app notification to Vendor
        $itemsStr = implode(', ', $vendorItemNames[$vEmail] ?? []);
        createNotification(
            $pdo,
            $vEmail,
            'vendor',
            '🌟 100 Loyalty Coins Awarded!',
            "Order $orderId ($itemsStr) was delivered! You earned 100 Loyalty Coins + ₦" . number_format($amount) . " in sales payout.",
            'loyalty_earned',
            '/vendor'
        );
    }

    // Send in-app notification to Buyer/Customer
    $stmtOrd = $pdo->prepare("SELECT user_email FROM orders WHERE id = ?");
    $stmtOrd->execute([$orderId]);
    $userEmail = $stmtOrd->fetchColumn() ?: '';

    createNotification(
        $pdo,
        $userEmail,
        'customer',
        '📦 Order Delivered!',
        "Order $orderId has been delivered successfully. Thank you for shopping on SulejaMarket!",
        'order_status',
        '/orders/' . $orderId
    );
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $action = $_GET['action'] ?? '';

    if ($action === 'place') {
        $id = !empty($data['id']) ? $data['id'] : uniqid('ord_');
        $userEmail = !empty($data['user_email']) ? $data['user_email'] : 'guest@example.com';
        $pdo->beginTransaction();
        
        try {
            $stmt = $pdo->prepare("INSERT INTO orders (id, user_email, subtotal, shipping, total, paymentMethod, paymentRef, status, driverPhone, createdAt) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $id, 
                $userEmail,
                $data['subtotal'], 
                $data['shipping'], 
                $data['total'], 
                $data['paymentMethod'] ?? '', 
                $data['paymentRef'] ?? '', 
                'placed',
                $data['driverPhone'] ?? '',
                time()
            ]);

            $stmtItem = $pdo->prepare("INSERT INTO order_items (order_id, product_id, name, price, seed, qty) VALUES (?, ?, ?, ?, ?, ?)");
            $vendorItems = [];
            foreach ($data['items'] as $item) {
                $stmtItem->execute([$id, $item['id'], $item['name'], $item['price'], $item['seed'], $item['qty']]);
                
                // Get product vendor email for notification
                $stmtP = $pdo->prepare("SELECT vendorEmail FROM products WHERE id = ?");
                $stmtP->execute([$item['id']]);
                $vEmail = $stmtP->fetchColumn();
                if ($vEmail) {
                    if (!isset($vendorItems[$vEmail])) $vendorItems[$vEmail] = [];
                    $vendorItems[$vEmail][] = $item['qty'] . 'x ' . $item['name'];
                }
            }

            $stmtHist = $pdo->prepare("INSERT INTO order_history (order_id, status, at) VALUES (?, ?, ?)");
            $stmtHist->execute([$id, 'placed', time()]);

            // Dispatch Customer Notification
            createNotification(
                $pdo,
                $userEmail,
                'customer',
                '🛒 Order Placed Successfully',
                "Order $id has been placed! Total: ₦" . number_format($data['total']) . ". We are processing your items.",
                'order_placed',
                '/orders/' . $id
            );

            // Dispatch Vendor Notifications
            foreach ($vendorItems as $vEmail => $itemsList) {
                createNotification(
                    $pdo,
                    $vEmail,
                    'vendor',
                    '🛍️ New Order Received!',
                    "New sale! Order $id placed for " . implode(', ', $itemsList) . ".",
                    'order_placed',
                    '/vendor'
                );
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'id' => $id]);
        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else if ($action === 'update_driver_phone') {
        $id = $data['id'] ?? '';
        $driverPhone = $data['driverPhone'] ?? '';

        if (!$id) {
            http_response_code(400);
            echo json_encode(['error' => 'Order ID required']);
            exit;
        }

        try {
            $stmt = $pdo->prepare("UPDATE orders SET driverPhone = ? WHERE id = ?");
            $success = $stmt->execute([$driverPhone, $id]);
            echo json_encode(['success' => $success, 'id' => $id, 'driverPhone' => $driverPhone]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else if ($action === 'advance') {
        $id = $data['id'];
        $stmt = $pdo->prepare("SELECT status, user_email FROM orders WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $curr = $row['status'] ?? '';
        $userEmail = $row['user_email'] ?? '';

        $flow = ['placed', 'processing', 'shipped', 'out_for_delivery', 'delivered'];
        $idx = array_search($curr, $flow);
        if ($idx !== false && $idx < count($flow) - 1) {
            $next = $flow[$idx + 1];
            
            $pdo->beginTransaction();
            try {
                $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$next, $id]);
                $pdo->prepare("INSERT INTO order_history (order_id, status, at) VALUES (?, ?, ?)")->execute([$id, $next, time()]);
                
                $statusLabels = [
                    'processing' => 'Packed & Processing',
                    'shipped' => 'Dispatched / Shipped',
                    'out_for_delivery' => 'Out for Delivery',
                    'delivered' => 'Delivered'
                ];
                $label = $statusLabels[$next] ?? $next;

                if ($next === 'delivered' && $curr !== 'delivered') {
                    processOrderDelivery($pdo, $id);
                } else {
                    createNotification(
                        $pdo,
                        $userEmail,
                        'customer',
                        '🚚 Order Status Updated',
                        "Order $id is now $label.",
                        'order_status',
                        '/orders/' . $id
                    );
                }

                $pdo->commit();
                echo json_encode(['success' => true, 'status' => $next]);
            } catch (Exception $e) {
                $pdo->rollBack();
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Cannot advance further']);
        }
    } else if ($action === 'update_status') {
        $id = $data['id'];
        $next = $data['status'];
        
        $stmt = $pdo->prepare("SELECT status, user_email FROM orders WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $curr = $row['status'] ?? '';
        $userEmail = $row['user_email'] ?? '';

        if ($curr !== $next) {
            $pdo->beginTransaction();
            try {
                $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$next, $id]);
                $pdo->prepare("INSERT INTO order_history (order_id, status, at) VALUES (?, ?, ?)")->execute([$id, $next, time()]);
                
                $statusLabels = [
                    'placed' => 'Placed',
                    'processing' => 'Packed & Processing',
                    'shipped' => 'Dispatched / Shipped',
                    'out_for_delivery' => 'Out for Delivery',
                    'delivered' => 'Delivered'
                ];
                $label = $statusLabels[$next] ?? $next;

                if ($next === 'delivered' && $curr !== 'delivered') {
                    processOrderDelivery($pdo, $id);
                } else {
                    createNotification(
                        $pdo,
                        $userEmail,
                        'customer',
                        '🚚 Order Status Updated',
                        "Order $id is now $label.",
                        'order_status',
                        '/orders/' . $id
                    );
                }
                
                $pdo->commit();
                echo json_encode(['success' => true, 'status' => $next]);
            } catch (Exception $e) {
                $pdo->rollBack();
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Status is already ' . $next]);
        }
    }
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $orders = $pdo->query("SELECT * FROM orders ORDER BY createdAt DESC")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($orders as &$ord) {
            $ord['driverPhone'] = $ord['driverPhone'] ?? '';

            $stmt = $pdo->prepare("SELECT product_id as id, name, price, seed, qty FROM order_items WHERE order_id = ?");
            $stmt->execute([$ord['id']]);
            $ord['items'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $pdo->prepare("SELECT * FROM order_history WHERE order_id = ?");
            $stmt->execute([$ord['id']]);
            $ord['history'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $ord['address'] = ['id' => '1', 'name' => 'Guest User', 'phone' => '08000000000', 'street' => '123 Main St', 'city' => 'Abuja', 'state' => 'FCT'];
        }
        echo json_encode($orders);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
