<?php
// Delivery Boy Orders API

require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// ✅ Get user ID safely (supports ?userId or ?user_id)
$userId = $_GET['userId'] ?? $_GET['user_id'] ?? null;

if (!$userId) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Delivery Boy User ID is required in the URL (e.g., ?userId=your-uuid).'
    ]);
    exit;
}

// ✅ Security check: Ensure this is a valid, active delivery boy
try {
    $stmt = $db->prepare("SELECT role FROM users WHERE id = :user_id AND is_active = 1 LIMIT 1");
    $stmt->bindParam(':user_id', $userId);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || strtolower($user['role']) !== 'delivery_boy') {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Access denied. Provided ID does not belong to an active delivery boy.'
        ]);
        exit;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error during user verification: ' . $e->getMessage()
    ]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        getDeliveryBoyOrders($db, $userId);
        break;

    case 'PUT':
        updateOrderStatus($db, $userId);
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}

/**
 * GET: Fetch delivery boy's assigned orders
 */
function getDeliveryBoyOrders($db, $deliveryBoyId)
{
    try {
        $status = $_GET['status'] ?? 'all';

        $whereClause = "WHERE o.delivery_boy_id = :delivery_boy_id";
        if ($status !== 'all') {
            $whereClause .= " AND o.status = :status";
        }

        $query = "
            SELECT 
                o.id, o.total_price, o.status, o.payment_status, o.payment_method,
                o.created_at, o.updated_at, o.delivery_token,
                u.name AS customer_name, u.phone AS customer_phone, u.email AS customer_email,
                a.address_line1, a.address_line2, a.city, a.state, a.postal_code,
                COUNT(oi.id) AS item_count,
                da.status AS assignment_status, da.assigned_at, da.notes
            FROM orders o
            JOIN users u ON o.user_id = u.id
            LEFT JOIN addresses a ON o.shipping_address_id = a.id
            LEFT JOIN order_items oi ON o.id = oi.order_id
            LEFT JOIN delivery_assignments da 
                ON o.id = da.order_id AND da.delivery_boy_id = o.delivery_boy_id
            $whereClause
            GROUP BY o.id
            ORDER BY o.created_at DESC
        ";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':delivery_boy_id', $deliveryBoyId);
        if ($status !== 'all') {
            $stmt->bindParam(':status', $status);
        }

        $stmt->execute();
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ✅ Fetch order items for each order
        foreach ($orders as &$order) {
            $itemsStmt = $db->prepare("
                SELECT 
                    oi.quantity, oi.unit_price, oi.total_price,
                    p.name AS product_name, p.brand, p.sku,
                    pv.variant_name,
                    pi.url AS image_url
                FROM order_items oi
                JOIN products p ON oi.product_id = p.id
                LEFT JOIN product_variants pv ON oi.variant_id = pv.id
                LEFT JOIN product_images pi 
                    ON p.id = pi.product_id AND pi.position = 0
                WHERE oi.order_id = :order_id
            ");
            $itemsStmt->bindParam(':order_id', $order['id']);
            $itemsStmt->execute();
            $order['items'] = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
        }

        echo json_encode(['success' => true, 'orders' => $orders]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

/**
 * PUT: Update order status (delivery boy)
 */
function updateOrderStatus($db, $deliveryBoyId)
{
    try {
        $data = json_decode(file_get_contents('php://input'), true);
        $orderId = $data['order_id'] ?? null;
        $status = $data['status'] ?? null;
        $notes = $data['notes'] ?? null;

        if (!$orderId || !$status) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Order ID and status required']);
            return;
        }

        $validStatuses = ['picked_up', 'out_for_delivery', 'delivered', 'failed'];
        if (!in_array($status, $validStatuses)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid status']);
            return;
        }

        // ✅ Start transaction
        $db->beginTransaction();

        // ✅ Get current order details for payment method check
        $orderCheck = $db->prepare("SELECT payment_method FROM orders WHERE id = :id AND delivery_boy_id = :delivery_boy_id");
        $orderCheck->execute([':id' => $orderId, ':delivery_boy_id' => $deliveryBoyId]);
        $order = $orderCheck->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            $db->rollBack();
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found or not assigned to you']);
            return;
        }

        // ✅ Update main order
        $orderStatus = ($status === 'delivered') ? 'delivered' : 'shipped';
        $paymentStatus = null;

        if ($status === 'delivered' && $order['payment_method'] === 'cash_on_delivery') {
            $paymentStatus = 'paid';
        }

        $updateSql = "
            UPDATE orders 
            SET status = :order_status, 
                updated_at = CURRENT_TIMESTAMP
                " . ($paymentStatus ? ", payment_status = :payment_status" : "") . "
            WHERE id = :order_id AND delivery_boy_id = :delivery_boy_id
        ";

        $stmt = $db->prepare($updateSql);
        $stmt->bindParam(':order_status', $orderStatus);
        if ($paymentStatus) {
            $stmt->bindParam(':payment_status', $paymentStatus);
        }
        $stmt->bindParam(':order_id', $orderId);
        $stmt->bindParam(':delivery_boy_id', $deliveryBoyId);
        $stmt->execute();

        // ✅ Update delivery assignment table
        $assignStmt = $db->prepare("
            UPDATE delivery_assignments 
            SET status = :status, notes = :notes, updated_at = CURRENT_TIMESTAMP
            WHERE order_id = :order_id AND delivery_boy_id = :delivery_boy_id
        ");
        $assignStmt->execute([
            ':status' => $status,
            ':notes' => $notes,
            ':order_id' => $orderId,
            ':delivery_boy_id' => $deliveryBoyId
        ]);

        $db->commit();

        $messages = [
            'picked_up' => 'Order marked as picked up',
            'out_for_delivery' => 'Order marked as out for delivery',
            'delivered' => 'Order marked as delivered',
            'failed' => 'Delivery marked as failed'
        ];

        echo json_encode([
            'success' => true,
            'message' => $messages[$status] ?? 'Order status updated'
        ]);
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

?>
