<?php
session_start();
require '../db.php';

$user_id = $_SESSION['user_id'] ?? null;
$store_id = $_SESSION['current_store_id'] ?? 1;

if (!$user_id) {
    echo json_encode(['status' => 'error', 'message' => 'User not found']);
    exit;
}

try {
    // Get active shift
    $stmt = $conn->prepare("SELECT id, start_time, opening_cash FROM shifts WHERE user_id = ? AND end_time IS NULL LIMIT 1");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $shift = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$shift) {
        echo json_encode(['status' => 'error', 'message' => 'No active shift found']);
        exit;
    }

    $shift_id = $shift['id'];
    $start_time = $shift['start_time'];
    $opening_cash = floatval($shift['opening_cash']);

    // Get sales summary by payment method
    $sales_stmt = $conn->prepare("
        SELECT 
            payment_method,
            COUNT(*) as transaction_count,
            SUM(total_amount) as total_amount,
            SUM(tax_amount) as total_tax,
            SUM(discount_amount) as total_discount,
            SUM(net_amount) as net_amount
        FROM sales 
        WHERE shift_id = ?
        GROUP BY payment_method
    ");
    $sales_stmt->bind_param("i", $shift_id);
    $sales_stmt->execute();
    $sales_result = $sales_stmt->get_result();
    $sales_summary = [];
    $total_sales = 0;
    $total_tax = 0;
    $total_discount = 0;
    $total_net = 0;
    
    while ($row = $sales_result->fetch_assoc()) {
        $sales_summary[] = $row;
        $total_sales += floatval($row['total_amount']);
        $total_tax += floatval($row['total_tax']);
        $total_discount += floatval($row['total_discount']);
        $total_net += floatval($row['net_amount']);
    }
    $sales_stmt->close();

    // Get cash sales specifically
    $cash_sales = 0;
    foreach ($sales_summary as $sale) {
        if ($sale['payment_method'] === 'cash') {
            $cash_sales = floatval($sale['total_amount']);
            break;
        }
    }

    // Get shift logs (cash in/out)
    $log_stmt = $conn->prepare("
        SELECT 
            action_type,
            SUM(amount) as total_amount,
            COUNT(*) as transaction_count
        FROM shift_logs 
        WHERE shift_id = ?
        GROUP BY action_type
    ");
    $log_stmt->bind_param("i", $shift_id);
    $log_stmt->execute();
    $log_result = $log_stmt->get_result();
    $shift_logs = [];
    $cash_in = 0;
    $cash_out = 0;
    
    while ($row = $log_result->fetch_assoc()) {
        $shift_logs[] = $row;
        if ($row['action_type'] === 'cash_in') {
            $cash_in = floatval($row['total_amount']);
        } elseif ($row['action_type'] === 'cash_out') {
            $cash_out = floatval($row['total_amount']);
        }
    }
    $log_stmt->close();

    // Calculate expected cash
    $expected_cash = $opening_cash + $cash_sales + $cash_in - $cash_out;

    // Get user info
    $user_stmt = $conn->prepare("SELECT username, email FROM users WHERE id = ?");
    $user_stmt->bind_param("i", $user_id);
    $user_stmt->execute();
    $user_info = $user_stmt->get_result()->fetch_assoc();
    $user_stmt->close();

    // Get store info
    $store_info = null;
    if ($store_id) {
        $store_stmt = $conn->prepare("SELECT store_name FROM stores WHERE id = ?");
        $store_stmt->bind_param("i", $store_id);
        $store_stmt->execute();
        $store_info = $store_stmt->get_result()->fetch_assoc();
        $store_stmt->close();
    }

    echo json_encode([
        'status' => 'success',
        'shift_data' => [
            'shift_id' => $shift_id,
            'start_time' => $start_time,
            'opening_cash' => $opening_cash,
            'expected_cash' => $expected_cash,
            'cash_sales' => $cash_sales,
            'cash_in' => $cash_in,
            'cash_out' => $cash_out
        ],
        'sales_summary' => $sales_summary,
        'shift_logs' => $shift_logs,
        'totals' => [
            'total_sales' => $total_sales,
            'total_tax' => $total_tax,
            'total_discount' => $total_discount,
            'total_net' => $total_net,
            'transaction_count' => array_sum(array_column($sales_summary, 'transaction_count'))
        ],
        'user_info' => $user_info,
        'store_info' => $store_info
    ]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
