<?php

require_once (dirname(__DIR__, 2) . '/init.php');
if (!m_admin_check()) {
	m_redirect(ADMIN_URL . '/login');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	@set_time_limit(300);
	@ignore_user_abort(true);
	$csrf_token = csrf_token($_POST['csrf_token']);
	if (!$csrf_token[0]) {
		if (($_POST['mode'] ?? '') === 'ajax') {
			@ob_clean();
			header('Content-Type: application/json; charset=utf-8');
			echo json_encode(['ok' => false, 'message' => ($csrf_token[1] ?? 'CSRF error')]);
			exit;
		} else {
			m_set_session('formSuccess', false);
			m_set_session('error_message', $csrf_token[1] ?? 'CSRF error');
			m_redirect($_SERVER['HTTP_REFERER']);
			exit;
		}
	}

	$db = new DB();
	$lang = m_get_session('admin_lang') ?: 'tr';
	$action = m_u_p('action');
	$manifestUrl = defined('UPDATE_MANIFEST_URL') ? UPDATE_MANIFEST_URL : trim($_POST['manifest_url'] ?? '');
	$mode = $_POST['mode'] ?? '';

	// Manifest URL sadece config veya önceden kayıtlı ayardan gelmeli; POST ile güncellenmez.

	$currentVersion = general_settings('app_version', $lang) ?: '1.0.0';

	// DB'deki mevcut app_version_[varsayılan] değerini oku (AJAX doğrulama için)
	if ($action === 'get_current') {
		if ($mode === 'ajax') {
			@ob_clean();
			header('Content-Type: application/json; charset=utf-8');
			$saveLang = lang_is_default('lang_code');
			$key = 'app_version_' . $saveLang;
			$row = $db->table('settings')->where('key_word', '=', $key)->get();
			$val = ($row['total_count'] ?? 0) > 0 ? ($row['data'][0]['value'] ?? null) : null;
			echo json_encode(['ok' => true, 'key' => $key, 'value' => $val]);
			exit;
		}
	}

	if ($action === 'check') {
		$resp = @m_url_get($manifestUrl);
		$data = @json_decode($resp, true);
		if ($mode === 'ajax') {
			@ob_clean();
			header('Content-Type: application/json; charset=utf-8');
			if (!is_array($data) || empty($data['latest'])) {
				echo json_encode(['ok' => false, 'message' => lang('updates.error.manifest')]);
				exit;
			}
			$latest = (string) $data['latest'];
			$pkg = isset($data['packages'][$latest]) ? (string) $data['packages'][$latest] : '';
			// Release notes (manifest farklı yapıları: sürüm -> notlar, dil -> notlar)
			$notes = '';
			if (isset($data['notes'])) {
				if (is_array($data['notes'])) {
					// 1) notes[latest] (sürüm anahtarına göre)
					if (isset($data['notes'][$latest])) {
						$notesVal = $data['notes'][$latest];
						$notes = is_array($notesVal) ? implode("\n", array_map('strval', $notesVal)) : (string)$notesVal;
					} else {
						// 2) notes[lang] (dil anahtarına göre)
						if (isset($data['notes'][$lang])) {
							$notesVal = $data['notes'][$lang];
							$notes = is_array($notesVal) ? implode("\n", array_map('strval', $notesVal)) : (string)$notesVal;
						} elseif (isset($data['notes']['tr'])) {
							$notesVal = $data['notes']['tr'];
							$notes = is_array($notesVal) ? implode("\n", array_map('strval', $notesVal)) : (string)$notesVal;
						} elseif (isset($data['notes']['en'])) {
							$notesVal = $data['notes']['en'];
							$notes = is_array($notesVal) ? implode("\n", array_map('strval', $notesVal)) : (string)$notesVal;
						} else {
							// 3) Dizi ise tüm değerleri birleştir
							$flat = [];
							foreach ($data['notes'] as $nv) { $flat[] = is_array($nv) ? implode("\n", array_map('strval', $nv)) : (string)$nv; }
							$notes = implode("\n\n", $flat);
						}
					}
				} elseif (is_string($data['notes'])) {
					$notes = (string)$data['notes'];
				}
			}
			if ($notes === '' && isset($data['releases']) && is_array($data['releases']) && isset($data['releases'][$latest])) {
				$rel = $data['releases'][$latest];
				if (is_array($rel) && isset($rel['notes'])) {
					$notesVal = $rel['notes'];
					$notes = is_array($notesVal) ? implode("\n", array_map('strval', $notesVal)) : (string)$notesVal;
				}
			}
			if ($notes === '') {
				$possible = ['changelog','changes','releaseNotes','whatsnew'];
				foreach ($possible as $k) {
					if (isset($data[$k])) {
						if (is_array($data[$k]) && isset($data[$k][$latest])) { $val = $data[$k][$latest]; $notes = is_array($val) ? implode("\n", array_map('strval', $val)) : (string)$val; break; }
						if (is_array($data[$k]) && isset($data[$k][$lang])) { $val = $data[$k][$lang]; $notes = is_array($val) ? implode("\n", array_map('strval', $val)) : (string)$val; break; }
						if (is_string($data[$k])) { $notes = (string)$data[$k]; break; }
					}
				}
			}
			$update = version_compare($latest, $currentVersion, '>');
			echo json_encode(['ok' => true, 'latest' => $latest, 'current' => $currentVersion, 'update' => $update, 'packageUrl' => $pkg, 'notes' => $notes]);
			exit;
		} else {
			if (!is_array($data) || empty($data['latest']) ) {
				$_SESSION['formSuccess'] = false;
				$_SESSION['error_message'] = lang('updates.error.manifest');
				m_redirect($_SERVER['HTTP_REFERER']);
				exit;
			}
			$latest = (string) $data['latest'];
			if (version_compare($latest, $currentVersion, '>')) {
				$_SESSION['formSuccess'] = true;
				$_SESSION['success_message'] = lang('updates.result.update_available', ['version' => $latest], 'Yeni sürüm mevcut: '.$latest);
			} else {
				$_SESSION['formSuccess'] = true;
				$_SESSION['success_message'] = lang('updates.result.up_to_date');
			}
			m_redirect($_SERVER['HTTP_REFERER']);
			exit;
		}
	}

	if ($action === 'update') {
		if (!class_exists('ZipArchive')) {
			if ($mode === 'ajax') {
				@ob_clean();
				header('Content-Type: application/json; charset=utf-8');
				echo json_encode(['ok' => false, 'message' => lang('updates.error.zip_missing')]);
				exit;
			} else {
				$_SESSION['formSuccess'] = false;
				$_SESSION['error_message'] = lang('updates.error.zip_missing');
				m_redirect($_SERVER['HTTP_REFERER']);
				exit;
			}
		}
		// AJAX modunda adımlı ilerle: download/extract/finalize
		if ($mode === 'ajax') {
			@ob_clean();
			header('Content-Type: application/json; charset=utf-8');
			$step = $_POST['step'] ?? 'download';
			// Manifesti oku
			$resp = @m_url_get($manifestUrl);
			$data = @json_decode($resp, true);
			if (!is_array($data) || empty($data['latest']) || empty($data['packages'][$data['latest']])) {
				echo json_encode(['ok' => false, 'message' => lang('updates.error.manifest')]);
				exit;
			}
			$latest = (string) $data['latest'];
			$packageUrl = (string) $data['packages'][$latest];
			if ($step === 'download') {
				$updatesDir = ROOT_FOLDER . '/updates';
				if (!is_dir($updatesDir)) { @mkdir($updatesDir, 0775, true); }
				$tmpZip = $updatesDir . '/update_' . preg_replace('/[^0-9a-zA-Z_.-]/','_', $latest) . '.zip';
				list($okDl, $resDl) = m_url_download_update($packageUrl, $tmpZip, null);
				if (!$okDl) { echo json_encode(['ok' => false, 'message' => 'download_failed', 'error' => $resDl]); exit; }
				$_SESSION['updates'] = ['zip' => $tmpZip, 'latest' => $latest];
				@session_write_close();
				echo json_encode(['ok' => true, 'message' => 'downloaded', 'zip' => $tmpZip, 'latest' => $latest]);
				exit;
			} elseif ($step === 'extract') {
				$zipPath = $_SESSION['updates']['zip'] ?? '';
				if (!$zipPath || !is_file($zipPath)) { echo json_encode(['ok' => false, 'message' => 'zip not found']); exit; }
				list($okEx, $msgEx) = m_zip_extract($zipPath, ROOT_FOLDER);
				if (!$okEx) { echo json_encode(['ok' => false, 'message' => $msgEx]); exit; }
				echo json_encode(['ok' => true, 'message' => 'extracted']);
				exit;
			} elseif ($step === 'finalize') {
				$zipPath = $_SESSION['updates']['zip'] ?? '';
				$latest = $_SESSION['updates']['latest'] ?? $latest;
				if ($zipPath && is_file($zipPath)) { @unlink($zipPath); }
				echo '<script>alert("sad")</script>';
				// Versiyonu her zaman varsayılan dil anahtarına yaz ki tüm dillerde görülsün
				$saveLang = lang_is_default('lang_code');
				$key = 'app_version_' . $saveLang;
				$saveOk = false;
				// Upsert dene: REPLACE INTO (key_word unique değilse yeni satır ekleyebilir)
				$rep = $db->query("REPLACE INTO settings (key_word, value) VALUES (?, ?)", [$key, $latest]);
				if ($rep !== false) {
					$saveOk = true;
				} else {
					// Fallback: update, sonra insert dene
					$saveOk = $db->table('settings')->where('key_word', '=', $key)->update(['value' => $latest, 'updated_at' => $db->now() ]);
					if (!$saveOk) {
						$saveOk = $db->table('settings')->insert(['key_word' => $key, 'value' => $latest, 'updated_at' => $db->now() ]);
						if (!$saveOk) { $saveOk = $db->table('settings')->insert(['key_word' => $key, 'value' => $latest]); }
					}
				}
				
				
				if (!$saveOk) {
					@ob_clean();
					header('Content-Type: application/json; charset=utf-8');
					echo json_encode(['ok' => false, 'message' => 'db_error', 'error' => $db->error(), 'key' => $key, 'latest' => $latest]);
					exit;
				}
				// Verify
				$verify = $db->table('settings')->where('key_word', '=', $key)->get();
				$verified = ($verify['total_count'] ?? 0) > 0 ? ($verify['data'][0]['value'] ?? null) : null;
				if ($verified !== $latest) {
					@ob_clean();
					header('Content-Type: application/json; charset=utf-8');
					echo json_encode(['ok' => false, 'message' => 'db_verify_failed', 'key' => $key, 'expected' => $latest, 'actual' => $verified]);
					exit;
				}
				unset($_SESSION['updates']);
				@ob_clean();
				header('Content-Type: application/json; charset=utf-8');
				$successPayload = [
					'ok' => true,
					'message' => 'finalized',
					'key' => $key,
					'latest' => $latest,
					'verified' => $verified,
					'db' => [ 'name' => (defined('DB_NAME') ? DB_NAME : null), 'table' => 'settings' ]
				];
				echo json_encode($successPayload);
				exit;
			}
			// bilinmeyen adım
			echo json_encode(['ok' => false, 'message' => 'bad step']);
			exit;
		}

		// non-ajax eski akış (tamamını tek seferde yapar)
		$resp = @m_url_get($manifestUrl);
		$data = @json_decode($resp, true);
		if (!is_array($data) || empty($data['latest']) || empty($data['packages'][$data['latest']])) {
			$_SESSION['formSuccess'] = false;
			$_SESSION['error_message'] = lang('updates.error.manifest');
			m_redirect($_SERVER['HTTP_REFERER']);
			exit;
		}
		$latest = (string) $data['latest'];
		$packageUrl = (string) $data['packages'][$latest];
		$updatesDir = ROOT_FOLDER . '/updates'; if (!is_dir($updatesDir)) { @mkdir($updatesDir, 0775, true); }
		$tmpZip = $updatesDir . '/update_' . preg_replace('/[^0-9a-zA-Z_.-]/','_', $latest) . '.zip';
		list($okDl, $resDl) = m_url_download_update($packageUrl, $tmpZip, null);
		if (!$okDl) { $_SESSION['formSuccess'] = false; $_SESSION['error_message'] = 'download_failed'; m_redirect($_SERVER['HTTP_REFERER']); exit; }
		list($okEx, $msgEx) = m_zip_extract($tmpZip, ROOT_FOLDER);
		if ($okEx) {
			@unlink($tmpZip);
			$key = 'app_version_' . $lang; $exists = $db->table('settings')->where('key_word', '=', $key)->get();
			if (($exists['total_count'] ?? 0) > 0) { $db->table('settings')->where('key_word', '=', $key)->update(['value' => $latest, 'updated_at' => $db->now() ]); }
			else { $db->table('settings')->insert(['key_word' => $key, 'value' => $latest, 'updated_at' => $db->now() ]); }
			$_SESSION['formSuccess'] = true; $_SESSION['success_message'] = lang('updates.success.updated');
		} else { $_SESSION['formSuccess'] = false; $_SESSION['error_message'] = (string)$msgEx; }
		m_redirect($_SERVER['HTTP_REFERER']);
		exit;
	}
}

http_response_code(405);
exit;

