<?php
session_start();
include 'shikanisha.kts.php';

header('Content-Type: application/json');

// Performance settings
ini_set('memory_limit', '512M');
set_time_limit(300);

try {
    // Authentication check
    if (!isset($_SESSION['type'], $_SESSION['user'])) {
        throw new Exception('Unauthorized access');
    }

    $userType = $_SESSION['type'];
    $userName = $_SESSION['user'];
    $requestType = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_STRING);

    if (!in_array($requestType, ['pending', 'today'])) {
        throw new Exception('Invalid request type');
    }

    // Pagination
    $limit = isset($_GET['limit']) ? max((int)$_GET['limit'], 1) : 100;
    $offset = isset($_GET['offset']) ? max((int)$_GET['offset'], 0) : 0;

    // Base query
    $query = "SELECT trans_id, seller_name, total, amount_received, 
                     payment_method, phone_number, seller_date
              FROM transaction_receipts";

    $conditions = [];
    $params = [];
    $types = '';

    if ($requestType === 'pending') {
        $conditions[] = "amount_received < total";
    } elseif ($requestType === 'today') {
        // For cashiers - get their active shift time range
        if ($userType === 'Cashier') {
            // Get active shift (where end_time is NULL or in future)
            $shiftQuery = "SELECT start_time 
                          FROM shifts 
                          JOIN employees ON shifts.employee_id = employees.employee_id
                          WHERE employees.username = ?
                          AND employees.type = 'Cashier'
                          AND (shifts.end_time IS NULL OR shifts.end_time > NOW())
                          ORDER BY start_time DESC
                          LIMIT 1";
            
            $shiftStmt = $conn->prepare($shiftQuery);
            $shiftStmt->bind_param('s', $userName);
            $shiftStmt->execute();
            $shiftResult = $shiftStmt->get_result();
            
            if ($shiftRow = $shiftResult->fetch_assoc()) {
                // Use shift start time and current time as range
                $start_datetime = $shiftRow['start_time'];
                $end_datetime = date('Y-m-d H:i:s'); // Current time
            } else {
                // If no active shift, fall back to today's transactions
                $start_datetime = date('Y-m-d 00:00:00');
                $end_datetime = date('Y-m-d 23:59:59');
            }
            $shiftStmt->close();
        } else {
            // For non-cashiers, use standard company day (5AM to next day 4:59AM)
            $start_datetime = date('Y-m-d 05:00:00');
            $end_datetime = date('Y-m-d 04:59:59', strtotime('+1 day'));
        }

        $conditions[] = "seller_date BETWEEN ? AND ?";
        $params[] = $start_datetime;
        $params[] = $end_datetime;
        $types .= 'ss';
    }

    // User-specific filtering (for non-manager/non-cashier)
    if (!in_array($userType, ['Manager', 'Cashier'])) {
        $conditions[] = "seller_name = ?";
        $params[] = $userName;
        $types .= 's';
    }

    // Build final query
    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }

    // Add pagination and sorting
    $query .= " ORDER BY seller_date DESC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    $types .= 'ii';

    // Execute main query
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $result = $stmt->get_result();

    // Stream data as JSON array
    $first = true;
    echo '[';
    while ($row = $result->fetch_assoc()) {
        if (!$first) echo ',';
        echo json_encode($row);
        $first = false;
    }
    echo ']';

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}