<?php
header('Content-Type: application/json');
require './shikanisha.kts.php';

// Calculate 18% of total beverage sales
function getBeverageSalesTotal($conn) {
    $query = "SELECT SUM(subtotal) AS total FROM sales WHERE category = 'Beverages'";
    $result = $conn->query($query);
    $row = $result->fetch_assoc();
    return $row['total'] * 0.18;
}

// Generate random sales in separate table
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $targetAmount = getBeverageSalesTotal($conn);
    $generatedAmount = 0;
    $generatedSales = [];
    
    // Get random active shift
    $shiftQuery = "SELECT s.shift_id, s.start_time, s.end_time 
                  FROM shifts s
                  WHERE s.status = 'active'
                  ORDER BY RAND() LIMIT 1";
    $shift = $conn->query($shiftQuery)->fetch_assoc();
    
    // Get random transaction from shift
    $transQuery = "SELECT trans_id, order_employee_id 
                  FROM transaction_receipts 
                  WHERE shift_id = {$shift['shift_id']}
                  ORDER BY RAND() LIMIT 1";
    $transaction = $conn->query($transQuery)->fetch_assoc();
    
    // Get beverage products
    $productsQuery = "SELECT product_id, product_name, selling_price, bp 
                     FROM sales 
                     WHERE category = 'Beverages'
                     GROUP BY product_id";
    $products = $conn->query($productsQuery);
    $productList = $products->fetch_all(MYSQLI_ASSOC);
    
    // Generate sales
    while ($generatedAmount < $targetAmount) {
        $product = $productList[array_rand($productList)];
        $quantity = rand(1, 3);
        $subtotal = $product['selling_price'] * $quantity;
        
        if (($generatedAmount + $subtotal) > $targetAmount) {
            $subtotal = $targetAmount - $generatedAmount;
            $quantity = ceil($subtotal / $product['selling_price']);
            $subtotal = $product['selling_price'] * $quantity;
        }
        
        $generatedSales[] = [
            'product_id' => $product['product_id'],
            'product_name' => $product['product_name'],
            'quantity' => $quantity,
            'selling_price' => $product['selling_price'],
            'subtotal' => $subtotal,
            'bp' => $product['bp'],
            'trans_id' => $transaction['trans_id'],
            'category' => 'Beverages'
        ];
        
        $generatedAmount += $subtotal;
    }
    
    // Insert into generated_sales table (not the main sales table)
    foreach ($generatedSales as $sale) {
        $insertQuery = "INSERT INTO generated_sales 
                        (product_id, product_name, quantity, selling_price, subtotal, trans_id, category, bp)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($insertQuery);
        $stmt->bind_param(
            "ssiddssd",
            $sale['product_id'],
            $sale['product_name'],
            $sale['quantity'],
            $sale['selling_price'],
            $sale['subtotal'],
            $sale['trans_id'],
            $sale['category'],
            $sale['bp']
        );
        $stmt->execute();
    }
    
    echo json_encode([
        
        'success' => true,
        'message' => "Generated " . count($generatedSales) . " beverage sales totaling $" . number_format($generatedAmount, 2),
        'sales' => $generatedSales,
        'total' => $generatedAmount,
        'formatted_target' => number_format($targetAmount, 2)
    ]);
    exit;
}

// Get current 18% target
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $target = getBeverageSalesTotal($conn);
    echo json_encode([
        'success' => true,
        'target' => $target,
        'formatted_target' => number_format($target, 2)
    ]);
    exit;
}