<?php
/**
 * PWA Background Sync - Sync Counts from Offline Operations
 * 
 * POST /api/sync-counts
 * Receives pending count data from offline storage and syncs to database
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Check authentication
if (!SessionManager::isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get JSON payload
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['counts']) || !is_array($input['counts'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid payload']);
    exit;
}

$counts = $input['counts'];
$syncedIds = [];
$errors = [];

try {
    $db = new Database();
    
    foreach ($counts as $count) {
        try {
            // Validate required fields
            if (empty($count['item_id']) || !isset($count['quantity'])) {
                $errors[] = "Invalid count record: missing required fields";
                continue;
            }

            // Check if item assignment exists
            $assignment = $db->fetchOne(
                "SELECT * FROM assignments WHERE id = ? AND user_id = ?",
                [$count['item_id'], SessionManager::getUserId()]
            );

            if (!$assignment) {
                $errors[] = "Assignment not found: {$count['item_id']}";
                continue;
            }

            // Insert or update count record
            $result = $db->execute(
                "INSERT INTO counts (assignment_id, user_id, quantity, notes, counted_at)
                 VALUES (?, ?, ?, ?, NOW())
                 ON DUPLICATE KEY UPDATE
                 quantity = VALUES(quantity),
                 notes = VALUES(notes),
                 updated_at = NOW()",
                [
                    $assignment['id'],
                    SessionManager::getUserId(),
                    $count['quantity'],
                    $count['notes'] ?? null,
                ]
            );

            if ($result) {
                $syncedIds[] = $count['id'] ?? $assignment['id'];
            }
        } catch (Exception $e) {
            $errors[] = "Error syncing count: " . $e->getMessage();
        }
    }

    // Return response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'synced_ids' => $syncedIds,
        'synced_count' => count($syncedIds),
        'total_count' => count($counts),
        'errors' => $errors,
    ]);

} catch (Exception $e) {
    error_log('[PWA API] Sync error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Sync failed: ' . $e->getMessage(),
    ]);
}
