<?php
require_once 'shikanisha.kts.php';

// Function to get active shift ID
function getActiveShiftId($conn) {
    $sql = "SELECT shift_id FROM shifts WHERE status = 'active' LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['shift_id'];
    }
    return null;
}

// Main logic
$response = [];
$activeShiftId = getActiveShiftId($conn);

if ($activeShiftId) {
    // Get all employees in this shift
    $employeesSql = "SELECT employee_id FROM shifts WHERE shift_id = ?";
    $stmt = $conn->prepare($employeesSql);
    $stmt->bind_param("i", $activeShiftId);
    $stmt->execute();
    $employeesResult = $stmt->get_result();
    
    $employeeIds = [];
    while ($row = $employeesResult->fetch_assoc()) {
        $employeeIds[] = $row['employee_id'];
    }
    
    // Get sales data for this shift
    if (!empty($employeeIds)) {
        $placeholders = implode(',', array_fill(0, count($employeeIds), '?'));
        $salesSql = "SELECT SUM(amount_received) as total_payments, SUM(total) as total_sales 
                     FROM transaction_receipts 
                     WHERE order_employee_id IN ($placeholders) AND shift_id = ?";
        
        $stmt = $conn->prepare($salesSql);
        $types = str_repeat('i', count($employeeIds)) . 'i';
        $params = array_merge($employeeIds, [$activeShiftId]);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $salesResult = $stmt->get_result();
        
        if ($salesResult->num_rows > 0) {
            $response = $salesResult->fetch_assoc();
            $response['shift_id'] = $activeShiftId;
            $response['outstanding'] = $response['total_sales'] - $response['total_payments'];
        }
    }
}

header('Content-Type: application/json');
echo json_encode($response);
$conn->close();
?>