<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

ini_set('upload_max_filesize', '100M');
ini_set('post_max_size', '105M');
ini_set('max_execution_time', '600');
ini_set('max_input_time', '600');
ini_set('memory_limit', '512M');

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Check if this is a chunked upload or regular upload
$isChunked = isset($_POST['chunk']) && isset($_POST['chunks']);

if ($isChunked) {
    handleChunkedUpload();
} else {
    handleRegularUpload();
}

function handleChunkedUpload() {
    $chunk = (int)$_POST['chunk'];
    $chunks = (int)$_POST['chunks'];
    $fileType = $_POST['fileType'] ?? 'student';
    $batchId = $_POST['batchId'] ?? generateBatchId();
    
    $upload_dir = '../uploads/excel/large_files/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $filename = $batchId . '_' . basename($_FILES['file']['name']);
    $filepath = $upload_dir . $filename;
    
    // Open temp file
    $out = fopen($filepath, $chunk == 0 ? "wb" : "ab");
    if ($out) {
        $in = fopen($_FILES['file']['tmp_name'], "rb");
        if ($in) {
            while ($buff = fread($in, 4096)) {
                fwrite($out, $buff);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to open input stream']);
            return;
        }
        fclose($in);
        fclose($out);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to open output stream']);
        return;
    }
    
    // If this is the last chunk, process the file
    if ($chunk == $chunks - 1) {
        processLargeFile($filepath, $fileType, $batchId);
    } else {
        echo json_encode([
            'success' => true,
            'message' => 'Chunk uploaded successfully',
            'chunk' => $chunk,
            'total_chunks' => $chunks,
            'batch_id' => $batchId
        ]);
    }
}

function handleRegularUpload() {
    if (!isset($_FILES['file'])) {
        echo json_encode(['success' => false, 'message' => 'No file uploaded']);
        return;
    }
    
    $file = $_FILES['file'];
    $fileType = $_POST['fileType'] ?? 'student';
    $batchId = generateBatchId();
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode([
            'success' => false,
            'message' => 'Upload error: ' . $file['error']
        ]);
        return;
    }
    
    $upload_dir = '../uploads/excel/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $filename = $batchId . '_' . basename($file['name']);
    $filepath = $upload_dir . $filename;
    
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        echo json_encode(['success' => false, 'message' => 'Failed to save file']);
        return;
    }
    
    // For files larger than 5MB, process in background
    if ($file['size'] > 5 * 1024 * 1024) {
        echo json_encode([
            'success' => true,
            'message' => 'Large file uploaded. Processing in background...',
            'batch_id' => $batchId,
            'filename' => $filename,
            'background_processing' => true
        ]);
        
        // Start background processing
        startBackgroundProcessing($filepath, $fileType, $batchId);
    } else {
        processLargeFile($filepath, $fileType, $batchId);
    }
}

function processLargeFile($filepath, $fileType, $batchId) {
    try {
        require_once '../vendor/autoload.php';
        
        // Create batch queue entry
        $conn = getDBConnection();
        if (!$conn) {
            throw new Exception('Database connection failed');
        }
        
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filepath);
        $worksheet = $spreadsheet->getActiveSheet();
        $rows = $worksheet->toArray();
        $totalRows = count($rows) - 1; // Subtract header
        
        // Insert into batch queue
        $queueStmt = $conn->prepare("
            INSERT INTO batch_queue (batch_id, file_type, filename, total_records, status) 
            VALUES (?, ?, ?, ?, 'pending')
        ");
        $queueStmt->bind_param("sssi", $batchId, $fileType, basename($filepath), $totalRows);
        $queueStmt->execute();
        $queueStmt->close();
        
        $conn->close();
        
        echo json_encode([
            'success' => true,
            'message' => 'File uploaded and queued for processing',
            'batch_id' => $batchId,
            'total_records' => $totalRows,
            'file_type' => $fileType,
            'status_url' => 'api/get_batch_status.php?batch_id=' . $batchId
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error processing file: ' . $e->getMessage()
        ]);
    }
}

function startBackgroundProcessing($filepath, $fileType, $batchId) {
    // This would trigger a background job
    // For now, we'll just process directly
    // In production, use cron jobs or queue workers
    processFileInBackground($filepath, $fileType, $batchId);
}

function processFileInBackground($filepath, $fileType, $batchId) {
    // This function would be called by a cron job or queue worker
    // For simplicity, we'll implement direct processing
    
    $logFile = '../uploads/excel/processing_logs/' . $batchId . '.log';
    $logDir = dirname($logFile);
    if (!file_exists($logDir)) {
        mkdir($logDir, 0777, true);
    }
    
    file_put_contents($logFile, "Starting processing for batch: $batchId\n", FILE_APPEND);
    
    // In production, this would be a separate script called by cron
    // For now, we'll just note that processing should happen
}

function generateBatchId() {
    return 'BATCH_' . date('YmdHis') . '_' . substr(md5(uniqid()), 0, 8);
}
?>