<?php

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../middleware/auth.php';
require_once __DIR__ . '/../helpers/response.php';

// ============================================
// CRIA CONEXÃO COM BANCO
// ============================================

$db = Database::getConnection();

// ============================================
// AUTENTICAÇÃO
// ============================================

$company = authenticateCompany();
$companyId = $company['id'];

// ============================================
// PARSE DO PAYLOAD
// ============================================

$payload = json_decode(file_get_contents('php://input'), true);

if (!$payload || !isset($payload['items']) || !is_array($payload['items'])) {
    jsonResponse(['error' => 'Invalid payload. Expected {"items": [...]}'], 400);
}

$items = $payload['items'];
$usuario = $payload['usuario'] ?? 'desktop';

// ============================================
// VALIDAÇÃO: CAMPOS OBRIGATÓRIOS POR ITEM
// ============================================

$invalidItems = [];

foreach ($items as $index => $item) {
    $errors = [];
    
    // Valida customer.email
    if (empty($item['customer']['email'])) {
        $errors[] = 'missing customer.email';
    }
    
    // Valida receivable.order_number
    if (empty($item['receivable']['order_number'])) {
        $errors[] = 'missing receivable.order_number';
    }
    
    // Valida receivable.document_number
    if (empty($item['receivable']['document_number'])) {
        $errors[] = 'missing receivable.document_number';
    }
    
    if (!empty($errors)) {
        $invalidItems[] = [
            'item_index' => $index,
            'document_number' => $item['receivable']['document_number'] ?? 'unknown',
            'errors' => $errors
        ];
    }
}

// Se houver itens inválidos, REJEITA TUDO!
if (!empty($invalidItems)) {
    jsonResponse([
        'error' => 'Invalid items found',
        'invalid_items' => $invalidItems,
        'message' => 'Fix these items and try again'
    ], 400);
}

// ============================================
// VALIDAÇÃO: LIMITE DE ITENS
// ============================================

if (count($items) === 0) {
    jsonResponse(['error' => 'No items provided'], 400);
}

// Busca limite do banco
$stmt = $db->prepare('SELECT setting_value FROM system_settings WHERE setting_key = "batch_max_items"');
$stmt->execute();
$result = $stmt->get_result();
$maxItems = $result->num_rows > 0 ? (int)$result->fetch_assoc()['setting_value'] : 100;

if (count($items) > $maxItems) {
    jsonResponse(['error' => "Too many items. Maximum is {$maxItems}"], 400);
}

// ============================================
// AGRUPA ITENS POR PEDIDO (EMAIL + ORDER_NUMBER)
// ============================================

$groupedByOrder = [];

foreach ($items as $item) {
    $email = strtolower(trim($item['customer']['email']));
    $orderNumber = trim($item['receivable']['order_number']);
    
    // Chave única: email|order_number
    $groupKey = $email . '|' . $orderNumber;
    
    if (!isset($groupedByOrder[$groupKey])) {
        $groupedByOrder[$groupKey] = [
            'customer' => $item['customer'],
            'order_number' => $orderNumber,
            'receivables' => []
        ];
    }
    
    $groupedByOrder[$groupKey]['receivables'][] = $item['receivable'];
}

// ============================================
// CRIA O JOB
// ============================================

$db->begin_transaction();

try {
    
    // Gera UUID único pro job
    $jobUuid = sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
    
    $ipOrigem = $_SERVER['REMOTE_ADDR'] ?? null;
    $totalItems = count($items);
    
    // Insere job
    $stmt = $db->prepare(
        'INSERT INTO batch_jobs 
         (company_id, job_uuid, total_items, usuario_desktop, ip_origem, created_at)
         VALUES (?, ?, ?, ?, ?, NOW())'
    );
    $stmt->bind_param('isiss', 
        $companyId, 
        $jobUuid, 
        $totalItems,
        $usuario,
        $ipOrigem
    );
    $stmt->execute();
    $jobId = $stmt->insert_id;
    
    // ============================================
    // INSERE OS ITENS AGRUPADOS
    // ============================================
    
    $stmt = $db->prepare(
        'INSERT INTO batch_items 
         (batch_job_id, document_number, customer_name, customer_email, amount, payload, created_at)
         VALUES (?, ?, ?, ?, ?, ?, NOW())'
    );
    
    foreach ($groupedByOrder as $groupKey => $group) {
        
        $email = $group['customer']['email'];
        $orderNumber = $group['order_number'];  
        $customerName = $group['customer']['name'] ?? null;
        
        // Para cada receivable desse pedido
        foreach ($group['receivables'] as $receivable) {
            
            $documentNumber = $receivable['document_number'] ?? null;
            $amount = $receivable['amount'] ?? 0;
            
            // Monta payload completo (customer + receivable individual)
            $itemPayload = [
                'customer' => $group['customer'],
                'receivable' => $receivable,
                'grouped_email' => $email,
                'grouped_order' => $orderNumber, // ADICIONA ORDER_NUMBER
                'total_items_in_group' => count($group['receivables'])
            ];
            
            $payloadJson = json_encode($itemPayload);
            
            $stmt->bind_param('isssds',
                $jobId,
                $documentNumber,
                $customerName,
                $email,
                $amount,
                $payloadJson
            );
            $stmt->execute();
        }
    }
    
    $db->commit();
    
    // ============================================
    // RESPOSTA IMEDIATA
    // ============================================
    
    jsonResponse([
        'success' => true,
        'job_id' => $jobUuid,
        'batch_id' => $jobId,
        'total_items' => $totalItems,
        'grouped_orders' => count($groupedByOrder),
        'status' => 'pending',
        'message' => 'Lote recebido e será processado em breve'
    ], 201);
    
} catch (Exception $e) {
    $db->rollback();
    
    error_log('Batch Send Error: ' . $e->getMessage());
    jsonResponse(['error' => 'Failed to create batch job'], 500);
}