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

require_once '../config/database.php';

$batchId = $_GET['batch_id'] ?? $_POST['batch_id'] ?? null;
$action = $_GET['action'] ?? $_POST['action'] ?? 'status';

if (!$batchId) {
    echo json_encode(['success' => false, 'message' => 'Batch ID required']);
    exit;
}

$conn = getDBConnection();
if (!$conn) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

switch ($action) {
    case 'status':
        getBatchStatus($conn, $batchId);
        break;
    case 'start':
        startBatchProcessing($conn, $batchId);
        break;
    case 'pause':
        pauseBatchProcessing($conn, $batchId);
        break;
    case 'resume':
        resumeBatchProcessing($conn, $batchId);
        break;
    case 'cancel':
        cancelBatchProcessing($conn, $batchId);
        break;
    case 'process_chunk':
        processChunk($conn, $batchId, $_POST['chunk_size'] ?? 100);
        break;
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

function getBatchStatus($conn, $batchId) {
    $stmt = $conn->prepare("
        SELECT b.*, 
               COUNT(p.id) as processed_count
        FROM batch_queue b
        LEFT JOIN processing_logs p ON b.batch_id = p.batch_id AND p.status = 'success'
        WHERE b.batch_id = ?
        GROUP BY b.id
    ");
    $stmt->bind_param("s", $batchId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $progress = $row['total_records'] > 0 ? 
            round(($row['processed_count'] / $row['total_records']) * 100) : 0;
        
        echo json_encode([
            'success' => true,
            'batch_id' => $batchId,
            'status' => $row['status'],
            'progress' => $progress,
            'processed' => $row['processed_count'],
            'total' => $row['total_records'],
            'success_count' => $row['success_count'],
            'error_count' => $row['error_count'],
            'started_at' => $row['started_at'],
            'completed_at' => $row['completed_at']
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Batch not found']);
    }
}

function startBatchProcessing($conn, $batchId) {
    // Get batch info
    $stmt = $conn->prepare("SELECT * FROM batch_queue WHERE batch_id = ?");
    $stmt->bind_param("s", $batchId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$batch = $result->fetch_assoc()) {
        echo json_encode(['success' => false, 'message' => 'Batch not found']);
        return;
    }
    
    // Update batch status
    $updateStmt = $conn->prepare("
        UPDATE batch_queue 
        SET status = 'processing', started_at = NOW() 
        WHERE batch_id = ?
    ");
    $updateStmt->bind_param("s", $batchId);
    $updateStmt->execute();
    
    // Process first chunk
    processChunk($conn, $batchId, 100);
}

function processChunk($conn, $batchId, $chunkSize = 100) {
    // This is a simplified version - you'd need to implement file reading
    // and processing logic here
    
    $updateStmt = $conn->prepare("
        UPDATE batch_queue 
        SET processed_records = processed_records + ?, 
            progress_percentage = ?
        WHERE batch_id = ?
    ");
    
    // Simulate progress for now
    $currentProgress = rand(10, 90);
    $updateStmt->bind_param("iis", $chunkSize, $currentProgress, $batchId);
    $updateStmt->execute();
    
    echo json_encode([
        'success' => true,
        'message' => 'Chunk processed',
        'progress' => $currentProgress
    ]);
}
?>