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

$localIP = trim(shell_exec('hostname -I | cut -d" " -f1'));

if (isset($_GET['mode'])) {
  if ($localIP == '192.168.15.10' && $_GET['mode'] == 'sender') {
    try {
    	$result = $conn->query("SHOW TABLES");
    	$tables = [];

    	while ($row = $result->fetch_array(MYSQLI_NUM)) {
    		$tables[] = $row[0];
    	}

    	$dump = [];

    	foreach ($tables as $table) {
    		$schema_result = $conn->query("DESCRIBE `$table`");
    		$schema = [];
    		while ($row = $schema_result->fetch_assoc()) {
    			$schema[] = $row;
    		}

    		$data_result = $conn->query("SELECT * FROM `$table`");
    		$data = [];
    		while ($row = $data_result->fetch_assoc()) {
    			$data[] = $row;
    		}

    		$dump[$table] = [
    			'schema' => $schema,
    			'data' => $data,
    			'count' => count($data)
    		];
    	}

    	$version = json_decode(file_get_contents(__DIR__ . '/version.json'), true);
    	$devplan = json_decode(file_get_contents(__DIR__ . '/devplan.json'), true);

    	echo json_encode([
    		'status' => 'success',
    		'database' => $serverdb,
    		'tables' => $dump,
    		'table_count' => count($tables),
    		'version' => $version,
    		'devplan' => $devplan
    	]);

    } catch (Exception $e) {
    	http_response_code(500);
    	echo json_encode([
    		'status' => 'error',
    		'message' => $e->getMessage()
    	]);
    }

  } else if ($localIP == '192.168.15.11' && $_GET['mode'] == 'importer') {
    $source_url = 'https://szaturnusz.szatuna.hu/managers/synch.php?mode=sender';

    try {
    	$response = file_get_contents($source_url);
    	$data = json_decode($response, true);

    	if ($data['status'] !== 'success') {
    		throw new Exception('Küldő hiba: ' . $data['message']);
    	}

    	$results = [];

    	foreach ($data['tables'] as $table => $table_data) {

        mysqli_query($conn, "TRUNCATE TABLE `$table`");

    		$rows = $table_data['data'];

    		if (empty($rows)) {
    			$results[$table] = 'Üres táblázat';
    			continue;
    		}

    		$columns = array_keys($rows[0]);
    		$placeholders = implode(',', array_map(fn($col) => "`$col`", $columns));
    		$values_placeholders = implode(',', array_fill(0, count($columns), '?'));
    		$updates = implode(',', array_map(fn($col) => "`$col`=VALUES(`$col`)", $columns));

    		$sql = "INSERT INTO `$table` ($placeholders) VALUES ($values_placeholders) ON DUPLICATE KEY UPDATE $updates";
    		$stmt = $conn->prepare($sql);

    		$types = str_repeat('s', count($columns));

    		$imported = 0;
    		foreach ($rows as $row) {
    			$values = array_values($row);
    			$stmt->bind_param($types, ...$values);
    			$stmt->execute();
    			$imported++;
    		}

    		$results[$table] = "$imported sor importálva";
    	}

    	file_put_contents(__DIR__ . '/version.json', json_encode($data['version'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    	file_put_contents(__DIR__ . '/devplan.json', json_encode($data['devplan'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

    	$results['version.json'] = 'Szinkronizálva';
    	$results['devplan.json'] = 'Szinkronizálva';

    	echo json_encode([
    		'status' => 'success',
    		'database' => $serverdb,
    		'results' => $results,
    		'table_count' => count($results)
    	]);

    } catch (Exception $e) {
    	http_response_code(500);
    	echo json_encode([
    		'status' => 'error',
    		'message' => $e->getMessage()
    	]);
    }

  }
}
?>
