<?php
// Delivery Management API
require_once '../config/cors.php';
require_once '../config/database.php';

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

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        handleGetRequest($db);
        break;
    case 'POST':
        handlePostRequest($db);
        break;
    case 'PUT':
        handlePutRequest($db);
        break;
    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}

function handleGetRequest($db) {
    $orderId = $_GET['order_id'] ?? null;
    $token = $_GET['token'] ?? null;
    
    if ($orderId) {
        // Get specific order for admin
        getOrderForAdmin($db, $orderId);
    } elseif ($token) {
        // Get order for delivery boy using token
        getOrderForDelivery($db, $token);
    } else {
        // Get all orders ready for delivery
        getDeliveryOrders($db);
    }
}

function handlePostRequest($db) {
    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? null;
    
    switch ($action) {
        case 'assign_delivery':
            assignDeliveryBoy($db, $data);
            break;
        case 'generate_delivery_link':
            generateDeliveryLink($db, $data);
            break;
        case 'get_delivery_boys':
            getActiveDeliveryBoys($db);
            break;
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
}

function handlePutRequest($db) {
    $data = json_decode(file_get_contents('php://input'), true);
    $token = $data['token'] ?? null;
    $action = $data['action'] ?? null;
    
    if (!$token) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Delivery token required']);
        return;
    }
    
    switch ($action) {
        case 'confirm_delivery':
            confirmDelivery($db, $token, $data);
            break;
        case 'confirm_payment':
            confirmPayment($db, $token);
            break;
        case 'report_issue':
            reportDeliveryIssue($db, $token, $data);
            break;
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
}

function getDeliveryOrders($db) {
    try {
        $status = $_GET['status'] ?? 'shipped';
        
        $stmt = $db->prepare("
            SELECT o.id, o.total_price, o.status, o.payment_status, o.payment_method,
                   o.delivery_boy_name, o.delivery_boy_phone, o.delivery_token,
                   o.created_at, o.updated_at,
                   u.name as customer_name, u.email as customer_email, u.phone as customer_phone,
                   a.address_line1, a.address_line2, a.city, a.state, a.postal_code,
                   COUNT(oi.id) as item_count
            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
            WHERE o.status IN ('confirmed', 'processing', 'shipped')
            GROUP BY o.id
            ORDER BY o.created_at DESC
        ");
        
        $stmt->execute();
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Add delivery links
        foreach ($orders as &$order) {
            if ($order['delivery_token']) {
                $order['delivery_link'] = "https://backmobile.rihancsccenter.in/api/admin/delivery.php?token=" . $order['delivery_token'];
            }
        }
        
        echo json_encode(['success' => true, 'orders' => $orders]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getOrderForAdmin($db, $orderId) {
    try {
        $stmt = $db->prepare("
            SELECT o.*, u.name as customer_name, u.email as customer_email, u.phone as customer_phone,
                   a.address_line1, a.address_line2, a.city, a.state, a.postal_code, a.label as address_label
            FROM orders o
            JOIN users u ON o.user_id = u.id
            LEFT JOIN addresses a ON o.shipping_address_id = a.id
            WHERE o.id = :order_id
        ");
        
        $stmt->bindParam(':order_id', $orderId);
        $stmt->execute();
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            return;
        }
        
        // Get order items
        $itemsStmt = $db->prepare("
            SELECT oi.*, 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', $orderId);
        $itemsStmt->execute();
        $order['items'] = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Add delivery link if token exists
        if ($order['delivery_token']) {
            $order['delivery_link'] = "https://backmobile.rihancsccenter.in/api/admin/delivery.php?token=" . $order['delivery_token'];
        }
        
        echo json_encode(['success' => true, 'order' => $order]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getOrderForDelivery($db, $token) {
    try {
        $stmt = $db->prepare("
            SELECT o.id, o.total_price, o.status, o.payment_status, o.payment_method,
                   o.delivery_boy_name, o.delivery_boy_phone, o.created_at,
                   u.name as customer_name, u.phone as customer_phone,
                   a.address_line1, a.address_line2, a.city, a.state, a.postal_code
            FROM orders o
            JOIN users u ON o.user_id = u.id
            LEFT JOIN addresses a ON o.shipping_address_id = a.id
            WHERE o.delivery_token = :token
        ");
        
        $stmt->bindParam(':token', $token);
        $stmt->execute();
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Invalid delivery token']);
            return;
        }
        
        // Get order items
        $itemsStmt = $db->prepare("
            SELECT oi.quantity, oi.unit_price, oi.total_price,
                   p.name as product_name, p.brand,
                   pv.variant_name
            FROM order_items oi
            JOIN products p ON oi.product_id = p.id
            LEFT JOIN product_variants pv ON oi.variant_id = pv.id
            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, 'order' => $order]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function assignDeliveryBoy($db, $data) {
    try {
        $orderIds = $data['order_ids'] ?? [$data['order_id'] ?? null];
        $deliveryBoyId = $data['delivery_boy_id'] ?? null;
        $assignedBy = $data['assigned_by'] ?? null; // Admin ID who is assigning
        
        // Remove null values from order IDs
        $orderIds = array_filter($orderIds);
        
        // If assigned_by is not provided, try to get it from headers or set a default admin
        if (!$assignedBy) {
            // Try to get from Authorization header or set default admin
            $headers = getallheaders();
            $authHeader = $headers['Authorization'] ?? '';
            
            if ($authHeader && strpos($authHeader, 'Bearer ') === 0) {
                $token = substr($authHeader, 7);
                // For now, let's get the first admin user as fallback
                $adminStmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' AND is_active = 1 LIMIT 1");
                $adminStmt->execute();
                $admin = $adminStmt->fetch(PDO::FETCH_ASSOC);
                $assignedBy = $admin['id'] ?? null;
            } else {
                // Fallback: get any admin user
                $adminStmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' AND is_active = 1 LIMIT 1");
                $adminStmt->execute();
                $admin = $adminStmt->fetch(PDO::FETCH_ASSOC);
                $assignedBy = $admin['id'] ?? null;
            }
        }
        
        if (empty($orderIds) || !$deliveryBoyId || !$assignedBy) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Order ID(s), delivery boy ID, and assigned by ID required']);
            return;
        }
        
        // Verify delivery boy exists and is active
        $deliveryBoyStmt = $db->prepare("
            SELECT id, name, phone FROM users 
            WHERE id = :id AND role = 'delivery_boy' AND is_active = 1
        ");
        $deliveryBoyStmt->bindParam(':id', $deliveryBoyId);
        $deliveryBoyStmt->execute();
        $deliveryBoy = $deliveryBoyStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$deliveryBoy) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Delivery boy not found or inactive']);
            return;
        }
        
        $db->beginTransaction();
        
        // Generate delivery token
        $deliveryToken = md5($deliveryBoy['name'] . 'delivery' . time());
        
        $updatedOrders = [];
        
        foreach ($orderIds as $orderId) {
            // Update order
            $stmt = $db->prepare("
                UPDATE orders 
                SET delivery_boy_id = :delivery_boy_id,
                    delivery_boy_name = :name, 
                    delivery_boy_phone = :phone, 
                    delivery_token = :token,
                    status = 'shipped',
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = :order_id AND status IN ('confirmed', 'processing')
            ");
            
            $stmt->bindParam(':delivery_boy_id', $deliveryBoyId);
            $stmt->bindParam(':name', $deliveryBoy['name']);
            $stmt->bindParam(':phone', $deliveryBoy['phone']);
            $stmt->bindParam(':token', $deliveryToken);
            $stmt->bindParam(':order_id', $orderId);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                // Create delivery assignment record
                $assignmentStmt = $db->prepare("
                    INSERT INTO delivery_assignments (order_id, delivery_boy_id, assigned_by, status)
                    VALUES (:order_id, :delivery_boy_id, :assigned_by, 'assigned')
                ");
                $assignmentStmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
                $assignmentStmt->bindParam(':delivery_boy_id', $deliveryBoyId, PDO::PARAM_STR);
                $assignmentStmt->bindParam(':assigned_by', $assignedBy, PDO::PARAM_STR);
                $assignmentStmt->execute();
                
                $updatedOrders[] = $orderId;
            }
        }
        
        if (!empty($updatedOrders)) {
            $db->commit();
            $deliveryLink = "https://backmobile.rihancsccenter.in/api/admin/delivery.php?token=" . $deliveryToken;
            
            echo json_encode([
                'success' => true, 
                'message' => count($updatedOrders) . ' order(s) assigned to ' . $deliveryBoy['name'] . ' successfully',
                'delivery_token' => $deliveryToken,
                'delivery_link' => $deliveryLink,
                'updated_orders' => $updatedOrders,
                'total_orders' => count($updatedOrders),
                'delivery_boy' => $deliveryBoy
            ]);
        } else {
            $db->rollBack();
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'No orders found or orders already assigned']);
        }
        
    } catch (Exception $e) {
        $db->rollBack();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function confirmDelivery($db, $token, $data) {
    try {
        $stmt = $db->prepare("
            UPDATE orders 
            SET status = 'delivered',
                payment_status = IF(payment_method = 'cash_on_delivery', 'paid', payment_status),
                updated_at = CURRENT_TIMESTAMP
            WHERE delivery_token = :token
        ");
        
        $stmt->bindParam(':token', $token);
        $stmt->execute();
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Order marked as delivered']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function confirmPayment($db, $token) {
    try {
        $stmt = $db->prepare("
            UPDATE orders 
            SET payment_status = 'paid',
                updated_at = CURRENT_TIMESTAMP
            WHERE delivery_token = :token
        ");
        
        $stmt->bindParam(':token', $token);
        $stmt->execute();
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Payment confirmed']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function reportDeliveryIssue($db, $token, $data) {
    try {
        $issue = $data['issue'] ?? 'Delivery issue reported';
        
        // For now, just log the issue. You can extend this to create a separate issues table
        error_log("Delivery Issue - Token: $token, Issue: $issue");
        
        echo json_encode(['success' => true, 'message' => 'Issue reported successfully']);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getActiveDeliveryBoys($db) {
    try {
        // Get registered delivery boys from users table
        $stmt = $db->prepare("
            SELECT u.id, u.name, u.phone, u.email, u.is_active,
                   COUNT(o.id) as active_orders,
                   GROUP_CONCAT(o.id) as order_ids
            FROM users u
            LEFT JOIN orders o ON u.id = o.delivery_boy_id AND o.status IN ('shipped', 'out_for_delivery')
            WHERE u.role = 'delivery_boy' AND u.is_active = 1
            GROUP BY u.id, u.name, u.phone, u.email, u.is_active
            ORDER BY u.name
        ");
        
        $stmt->execute();
        $deliveryBoys = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Process order IDs
        foreach ($deliveryBoys as &$boy) {
            $boy['order_ids'] = $boy['order_ids'] ? explode(',', $boy['order_ids']) : [];
            $boy['active_orders'] = (int)$boy['active_orders'];
        }
        
        echo json_encode(['success' => true, 'delivery_boys' => $deliveryBoys]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>