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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid shift ID']);
    exit;
}

$shiftId = (int)$_GET['id'];

// 1. Get Shift Basic Info
$shiftQuery = $conn->prepare("
    SELECT 
        s.shift_id, 
        s.start_time, 
        s.end_time, 
        s.total_orders, 
        s.total_payments, 
        s.total_debt,
        s.status,
        s.employee_id,
        e.name as employee_name
    FROM shifts s
    LEFT JOIN employees e ON s.employee_id = e.employee_id
    WHERE s.shift_id = ?
");
$shiftQuery->bind_param("i", $shiftId);
$shiftQuery->execute();
$shiftResult = $shiftQuery->get_result();

if ($shiftResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Shift not found']);
    exit;
}

$shift = $shiftResult->fetch_assoc();

// 2. Get All Transactions for This Shift
$transactions = [];
$transQuery = $conn->prepare("
    SELECT 
        trans_id,
        amount_received,
        total,
        seller_date,
        order_employee_id
    FROM transaction_receipts
    WHERE shift_id = ?
    ORDER BY seller_date DESC
");
$transQuery->bind_param("i", $shiftId);
$transQuery->execute();
$transResult = $transQuery->get_result();

while ($trans = $transResult->fetch_assoc()) {
    $transId = $trans['trans_id'];
    
    // 3. Get Sales Items for Each Transaction
    $salesItems = [];
    $salesQuery = $conn->prepare("
        SELECT 
            product_name,
            quantity,
            selling_price,
            subtotal,
            category,
            bp
        FROM sales
        WHERE trans_id = ?
    ");
    $salesQuery->bind_param("s", $transId);
    $salesQuery->execute();
    $salesResult = $salesQuery->get_result();
    
    while ($item = $salesResult->fetch_assoc()) {
        $salesItems[] = $item;
    }
    $trans['items'] = $salesItems;
    
    // 4. Get Payments for Each Transaction
    $payments = [];
    $paymentQuery = $conn->prepare("
        SELECT 
            payment_method,
            amount
        FROM payments
        WHERE trans_id = ?
    ");
    $paymentQuery->bind_param("s", $transId);
    $paymentQuery->execute();
    $paymentResult = $paymentQuery->get_result();
    
    while ($payment = $paymentResult->fetch_assoc()) {
        $payments[] = $payment;
    }
    $trans['payments'] = $payments;
    
    $transactions[] = $trans;
}

// 5. Calculate Summary Data
$summary = [
    'total_sales' => (float)$shift['total_orders'],
    'total_received' => (float)$shift['total_payments'],
    'total_debt' => (float)$shift['total_debt'],
    'transaction_count' => count($transactions),
    'payment_method_totals' => []
];

// Calculate payment method totals
foreach ($transactions as $trans) {
    foreach ($trans['payments'] as $payment) {
        $method = $payment['payment_method'];
        $summary['payment_method_totals'][$method] = 
            ($summary['payment_method_totals'][$method] ?? 0) + $payment['amount'];
    }
}

// 6. Prepare Final Response
$response = [
    'success' => true,
    'data' => [
        'shift' => $shift,
        'transactions' => $transactions,
        'summary' => $summary
    ]
];

echo json_encode($response);
$conn->close();
?>