<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$userId = $_SESSION['uid'];

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Set content type to JSON
header('Content-Type: application/json');

try {
    switch ($method) {
        case 'POST':
            createPendingOrder();
            break;
        case 'GET':
            if (isset($_GET['id'])) {
                getPendingOrder($_GET['id']);
            } else {
                getAllPendingOrders();
            }
            break;
        case 'PUT':
            updatePendingOrder();
            break;
        case 'DELETE':
            if (isset($_GET['id'])) {
                deletePendingOrder($_GET['id']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Order ID required']);
            }
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

// Create a new pending order
function createPendingOrder() {
    global $dbh, $userId;
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
        return;
    }
    
    // Validate required fields
    if (!isset($input['customer_id']) || !isset($input['cart_items']) || empty($input['cart_items'])) {
        echo json_encode(['success' => false, 'message' => 'Customer ID and cart items are required']);
        return;
    }
    
    try {
        $dbh->beginTransaction();
        
        // Generate order number
        $orderNumber = 'ORD' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
        
        // Check if order number already exists, regenerate if needed
        $checkStmt = $dbh->prepare("SELECT COUNT(*) FROM tblpendingorders WHERE OrderNumber = ?");
        $checkStmt->execute([$orderNumber]);
        while ($checkStmt->fetchColumn() > 0) {
            $orderNumber = 'ORD' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $checkStmt->execute([$orderNumber]);
        }
        
        // Calculate totals
        $subtotal = 0;
        foreach ($input['cart_items'] as $item) {
            $bagPrice = $item['rate'] * $item['bag_kg']; // rate per kg * kg per bag
            $subtotal += $bagPrice * $item['quantity'];
        }
        
        $discountAmount = isset($input['discount_amount']) ? floatval($input['discount_amount']) : 0;
        $totalAmount = $subtotal - $discountAmount;
        
        // Get cashier name
        $cashierStmt = $dbh->prepare("SELECT FullName FROM tblusers WHERE ID = ?");
        $cashierStmt->execute([$userId]);
        $cashierName = $cashierStmt->fetchColumn() ?: 'Unknown';
        
        // Insert pending order
        $orderStmt = $dbh->prepare("
            INSERT INTO tblpendingorders 
            (OrderNumber, OrderDate, OrderTime, CustomerID, SubTotal, DiscountAmount, TotalAmount, Notes, CashierID, CashierName)
            VALUES (?, CURDATE(), CURTIME(), ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $orderStmt->execute([
            $orderNumber,
            $input['customer_id'],
            $subtotal,
            $discountAmount,
            $totalAmount,
            $input['notes'] ?? '',
            $userId,
            $cashierName
        ]);
        
        $orderId = $dbh->lastInsertId();
        
        // Insert order items
        $itemStmt = $dbh->prepare("
            INSERT INTO tblpendingorderitems 
            (OrderID, ProductID, ProductName, Quantity, UnitPrice, LineTotal)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($input['cart_items'] as $item) {
            // Get product name
            $productStmt = $dbh->prepare("SELECT RiceBagName FROM tblricebags WHERE ID = ?");
            $productStmt->execute([$item['product_id']]);
            $productName = $productStmt->fetchColumn() ?: 'Unknown Product';
            
            $bagPrice = $item['rate'] * $item['bag_kg']; // rate per kg * kg per bag
            $lineTotal = $bagPrice * $item['quantity'];
            
            $itemStmt->execute([
                $orderId,
                $item['product_id'],
                $productName,
                $item['quantity'],
                $bagPrice,
                $lineTotal
            ]);
        }
        
        $dbh->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Order saved successfully',
            'data' => [
                'order_id' => $orderId,
                'order_number' => $orderNumber,
                'total_amount' => $totalAmount
            ]
        ]);
        
    } catch (Exception $e) {
        $dbh->rollback();
        throw $e;
    }
}

// Get all pending orders
function getAllPendingOrders() {
    global $dbh;
    
    $status = $_GET['status'] ?? 'Pending';
    $fromDate = $_GET['from_date'] ?? null;
    $toDate = $_GET['to_date'] ?? null;
    
    // Build the WHERE clause
    $whereClause = "WHERE po.OrderStatus = ?";
    $params = [$status];
    
    if ($fromDate && $toDate) {
        $whereClause .= " AND DATE(po.CreatedAt) BETWEEN ? AND ?";
        $params[] = $fromDate;
        $params[] = $toDate;
    }
    
    $stmt = $dbh->prepare("
        SELECT 
            po.*,
            c.CustomerName,
            c.Mobile,
            c.Area,
            c.Address,
            COUNT(poi.ID) as ItemCount
        FROM tblpendingorders po
        LEFT JOIN tblcustomers c ON po.CustomerID = c.ID
        LEFT JOIN tblpendingorderitems poi ON po.ID = poi.OrderID
        $whereClause
        GROUP BY po.ID
        ORDER BY po.CreatedAt DESC
    ");
    
    $stmt->execute($params);
    $orders = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $orders
    ]);
}

// Get single pending order with items
function getPendingOrder($orderId) {
    global $dbh;
    
    // Get order details
    $orderStmt = $dbh->prepare("
        SELECT 
            po.*,
            c.CustomerName,
            c.Mobile,
            c.Area,
            c.CustomerType
        FROM tblpendingorders po
        LEFT JOIN tblcustomers c ON po.CustomerID = c.ID
        WHERE po.ID = ?
    ");
    
    $orderStmt->execute([$orderId]);
    $order = $orderStmt->fetch();
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        return;
    }
    
    // Get order items
    $itemsStmt = $dbh->prepare("
        SELECT 
            poi.*,
            rb.RiceBagName,
            rb.BagKg,
            rb.RetailRate,
            rb.ShopRate,
            rb.StockInBags
        FROM tblpendingorderitems poi
        LEFT JOIN tblricebags rb ON poi.ProductID = rb.ID
        WHERE poi.OrderID = ?
        ORDER BY poi.ID
    ");
    
    $itemsStmt->execute([$orderId]);
    $items = $itemsStmt->fetchAll();
    
    $order['items'] = $items;
    
    echo json_encode([
        'success' => true,
        'data' => $order
    ]);
}

// Update pending order
function updatePendingOrder() {
    global $dbh;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['order_id'])) {
        echo json_encode(['success' => false, 'message' => 'Order ID required']);
        return;
    }
    
    try {
        $dbh->beginTransaction();
        
        $orderId = $input['order_id'];
        
        // Update order status and delivery info if provided
        if (isset($input['order_status'])) {
            $updateFields = ['OrderStatus = ?'];
            $params = [$input['order_status']];
            
            if ($input['order_status'] === 'Delivered') {
                $updateFields[] = 'DeliveryDate = CURDATE()';
                $updateFields[] = 'DeliveryTime = CURTIME()';
            }
            
            if (isset($input['notes'])) {
                $updateFields[] = 'Notes = ?';
                $params[] = $input['notes'];
            }
            
            $params[] = $orderId;
            
            $stmt = $dbh->prepare("
                UPDATE tblpendingorders 
                SET " . implode(', ', $updateFields) . "
                WHERE ID = ?
            ");
            
            $stmt->execute($params);
        }
        
        // Update items if provided
        if (isset($input['cart_items'])) {
            // Delete existing items
            $deleteStmt = $dbh->prepare("DELETE FROM tblpendingorderitems WHERE OrderID = ?");
            $deleteStmt->execute([$orderId]);
            
            // Recalculate totals
            $subtotal = 0;
            foreach ($input['cart_items'] as $item) {
                $bagPrice = $item['rate'] * $item['bag_kg'];
                $subtotal += $bagPrice * $item['quantity'];
            }
            
            $discountAmount = isset($input['discount_amount']) ? floatval($input['discount_amount']) : 0;
            $totalAmount = $subtotal - $discountAmount;
            
            // Update order totals
            $updateOrderStmt = $dbh->prepare("
                UPDATE tblpendingorders 
                SET SubTotal = ?, DiscountAmount = ?, TotalAmount = ?
                WHERE ID = ?
            ");
            $updateOrderStmt->execute([$subtotal, $discountAmount, $totalAmount, $orderId]);
            
            // Insert new items
            $itemStmt = $dbh->prepare("
                INSERT INTO tblpendingorderitems 
                (OrderID, ProductID, ProductName, Quantity, UnitPrice, LineTotal)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($input['cart_items'] as $item) {
                $productStmt = $dbh->prepare("SELECT RiceBagName FROM tblricebags WHERE ID = ?");
                $productStmt->execute([$item['product_id']]);
                $productName = $productStmt->fetchColumn() ?: 'Unknown Product';
                
                $bagPrice = $item['rate'] * $item['bag_kg'];
                $lineTotal = $bagPrice * $item['quantity'];
                
                $itemStmt->execute([
                    $orderId,
                    $item['product_id'],
                    $productName,
                    $item['quantity'],
                    $bagPrice,
                    $lineTotal
                ]);
            }
        }
        
        $dbh->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Order updated successfully'
        ]);
        
    } catch (Exception $e) {
        $dbh->rollback();
        throw $e;
    }
}

// Delete pending order
function deletePendingOrder($orderId) {
    global $dbh;
    
    try {
        $stmt = $dbh->prepare("DELETE FROM tblpendingorders WHERE ID = ?");
        $stmt->execute([$orderId]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Order deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Order not found']);
        }
        
    } catch (Exception $e) {
        throw $e;
    }
}
?>