<?php

namespace NixfilePlugin\Admin;


use NixfilePlugin\Api\Client;
use NixfilePlugin\Helper\Backup;
use NixfilePlugin\Plugin;

class Ajax {
	public static function list(): void {
		check_ajax_referer( "nixfile_gallery" );

		$folderId = sanitize_text_field( $_POST["folder_id"] ?? "" );
		$client   = new Client();
		$result   = $client->getFolder( $folderId );
		if ( ! isset( $result["success"] ) || ! $result["success"] ) {
			wp_send_json_error( "API request failed" );
		}

		$data = [
			"current_folder" => $result["data"]["current_folder"],
			"folders"        => $result["data"]["folders"],
			"files"          => $result["data"]["media"]["data"]
		];

		wp_send_json_success( $data );
	}

	public static function uploadFile(): void {
		check_ajax_referer( "nixfile_gallery" );

		if ( ! isset( $_FILES["file"] ) ) {
			wp_send_json_error( "No file received" );
		}

		$folderId = sanitize_text_field( $_POST["folder_id"] ?? "" );

		$tmp  = $_FILES["file"]["tmp_name"];
		$name = $_FILES["file"]["name"];

		$client = new Client();
		$result = $client->upload( $tmp, $name, $folderId );

		if ( ! isset( $result["success"] ) || ! $result["success"] ) {
			wp_send_json_error( $result );
		}

		wp_send_json_success( $result );
	}

	public static function updateSetting(): void {
		check_ajax_referer("nixfile_gallery");

		if (!isset($_POST['nixfile_settings']) || !is_array($_POST['nixfile_settings'])) {
			wp_send_json_error("No settings received");
		}
		$settings = $_POST['nixfile_settings'];
		$clean = [];
		foreach ($settings as $key => $value) {
			if ($value === "1") {
				$clean[$key] = 1;
			} else {
				$clean[$key] = sanitize_text_field($value);
			}
		}
		update_option(Plugin::optionKey(), $clean);
		$backupTriggered = false;
		if (isset($clean['daily_backup']) && $clean['daily_backup'] == 1) {

			if (class_exists(Backup::class)) {

				try {
					Backup::run();
					$backupTriggered = true;

				} catch (\Throwable $e) {
					wp_send_json_error([
						"message" => "Settings saved, but backup failed to run.",
						"error"   => $e->getMessage()
					]);
				}
			}
		}
		wp_send_json_success([
			"message" => "Settings saved successfully",
			"backup"  => $backupTriggered ? "Backup executed now" : "Backup not triggered",
			"saved"   => $clean
		]);
	}

}