<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    require_once '../config/db.php';
    
    // Get JSON data
    $input = file_get_contents('php://input');
    if (empty($input)) {
        throw new Exception('No data received');
    }
    
    $data = json_decode($input, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON: ' . json_last_error_msg());
    }

    // Make sure we're not in a transaction
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    // Start fresh transaction
    $pdo->beginTransaction();
    
    try {
        // Disable foreign key checks
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
        
        $tablesUpdated = 0;
        
        foreach ($data as $table => $rows) {
            if (empty($rows)) continue;
            
            // Clear existing data
            $pdo->exec("TRUNCATE TABLE `$table`");
            
            // Prepare insert statement
            $columns = array_keys($rows[0]);
            $placeholders = str_repeat('?,', count($columns) - 1) . '?';
            
            $sql = "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) 
                    VALUES ($placeholders)";
            
            $stmt = $pdo->prepare($sql);
            
            // Insert rows
            foreach ($rows as $row) {
                $stmt->execute(array_values($row));
            }
            
            $tablesUpdated++;
        }
        
        // Re-enable foreign key checks
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "Successfully updated $tablesUpdated tables",
            'tables' => $tablesUpdated
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        throw $e;
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'details' => [
            'timestamp' => date('Y-m-d H:i:s'),
            'php_version' => PHP_VERSION,
            'memory_used' => memory_get_usage(true) / 1024 / 1024 . 'MB'
        ]
    ]);
}
?>