<?php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) wp_die('Unauthorized');

if (!function_exists('afb_get_client_gateway_visibility_profiles')) {
	wp_die('Required gateway settings helpers are unavailable.');
}

$profiles = afb_get_client_gateway_visibility_profiles();
if (!isset($profiles['projects']) || !is_array($profiles['projects'])) {
	$profiles['projects'] = [];
}

$selected_project_gid = preg_replace('/\D+/', '', (string)($_REQUEST['project_gid'] ?? ''));

// Build project list from active Asana accounts (API), with cache fallback below.
$projects_map = [];
if (function_exists('afb_fetch_asana')) {
	global $wpdb;
	$account_table = $wpdb->prefix . 'asana_accounts';
	$accounts = $wpdb->get_results("SELECT * FROM $account_table WHERE active = 1 ORDER BY id DESC", ARRAY_A) ?: [];

	foreach ($accounts as $account) {
		$pat_raw = sanitize_text_field((string)($account['pat'] ?? ''));
		$pat = function_exists('afb_decrypt') ? (afb_decrypt($pat_raw) ?: $pat_raw) : $pat_raw;
		if ($pat === '') continue;

		$portfolio_gid = preg_replace('/\D+/', '', (string)($account['portfolio_gid'] ?? ''));
		$items = [];

		if ($portfolio_gid !== '' && function_exists('afb_get_portfolio_projects')) {
			$items = afb_get_portfolio_projects($portfolio_gid, $pat);
		} else {
			$res = afb_fetch_asana('projects?limit=200&opt_fields=gid,name', $pat);
			$items = (is_array($res) && isset($res['data']) && is_array($res['data'])) ? $res['data'] : (is_array($res) ? $res : []);
		}

		foreach ($items as $project) {
			$gid = preg_replace('/\D+/', '', (string)($project['gid'] ?? ''));
			if ($gid === '') continue;

			$name = sanitize_text_field((string)($project['name'] ?? ''));
			if (!isset($projects_map[$gid])) {
				$projects_map[$gid] = [
					'gid' => $gid,
					'name' => $name !== '' ? $name : ('Project ' . $gid),
				];
			}
		}
	}
}

$fields_by_project = [];
$cache_files = glob(trailingslashit(AFB_PLUGIN_DIR) . 'cache/tasks-summary-*.json') ?: [];
usort($cache_files, static function ($a, $b) {
	return filemtime($b) <=> filemtime($a);
});

$scan_limit = 30;
$scan_count = 0;

foreach ($cache_files as $path) {
	if ($scan_count >= $scan_limit) break;

	$raw = @file_get_contents($path);
	if ($raw === false) continue;

	$data = json_decode($raw, true);
	if (!is_array($data)) continue;

	$task = $data['parent'] ?? $data['task'] ?? $data;
	if (!is_array($task) || empty($task['custom_fields']) || !is_array($task['custom_fields'])) {
		continue;
	}

	$project_gid = preg_replace('/\D+/', '', (string)($task['projects'][0]['gid'] ?? ''));
	if ($project_gid === '') {
		continue;
	}

	$project_name = sanitize_text_field((string)($task['projects'][0]['name'] ?? ''));
	if (!isset($projects_map[$project_gid])) {
		$projects_map[$project_gid] = [
			'gid' => $project_gid,
			'name' => $project_name !== '' ? $project_name : ('Project ' . $project_gid),
		];
	}

	foreach ($task['custom_fields'] as $field) {
		$name = sanitize_text_field((string)($field['name'] ?? ''));
		if ($name === '') continue;

		$key = function_exists('afb_client_gateway_field_key')
			? afb_client_gateway_field_key($field)
			: 'name:' . sanitize_title($name);

		$type = sanitize_text_field((string)($field['type'] ?? 'unknown'));
		$gid  = sanitize_text_field((string)($field['gid'] ?? ''));

		if (!isset($fields_by_project[$project_gid])) {
			$fields_by_project[$project_gid] = [];
		}

		if (!isset($fields_by_project[$project_gid][$key])) {
			$fields_by_project[$project_gid][$key] = [
				'key' => $key,
				'name' => $name,
				'type' => $type,
				'gid' => $gid,
				'count' => 1,
			];
		} else {
			$fields_by_project[$project_gid][$key]['count']++;
		}
	}

	$scan_count++;
}

foreach ($fields_by_project as $gid => $rows) {
	uasort($rows, static function ($a, $b) {
		return strcasecmp($a['name'], $b['name']);
	});
	$fields_by_project[$gid] = $rows;
}

// Ensure projects already configured in saved settings are available on the landing list.
foreach (($profiles['projects'] ?? []) as $project_gid => $project_data) {
	$project_gid = preg_replace('/\D+/', '', (string)$project_gid);
	if ($project_gid === '') continue;

	if (!isset($projects_map[$project_gid])) {
		$saved_name = sanitize_text_field((string)($project_data['name'] ?? ''));
		$projects_map[$project_gid] = [
			'gid' => $project_gid,
			'name' => $saved_name !== '' ? $saved_name : ('Project ' . $project_gid),
		];
	}
}

$notice_message = '';
$notice_class = 'notice-success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['afb_save_cg_settings'])) {
	check_admin_referer('afb_save_cg_settings');

	$project_gid = preg_replace('/\D+/', '', (string)($_POST['project_gid'] ?? ''));
	if ($project_gid === '') {
		$notice_message = 'Missing project identifier. Settings were not saved.';
		$notice_class = 'notice-error';
	} else {
		$posted_hidden = $_POST['afb_cg_hidden_keys'] ?? [];
		if (!is_array($posted_hidden)) {
			$posted_hidden = [];
		}

		$hidden_clean = [];
		foreach ($posted_hidden as $key) {
			$key = sanitize_text_field((string) $key);
			if ($key !== '') {
				$hidden_clean[] = $key;
			}
		}
		$hidden_clean = array_values(array_unique($hidden_clean));

		$posted_creation_mode = strtolower(sanitize_text_field((string)($_POST['afb_cg_creation_mode'] ?? 'manual')));
		if (!in_array($posted_creation_mode, ['manual', 'automatic'], true)) {
			$posted_creation_mode = 'manual';
		}

		$project_name = sanitize_text_field((string)($projects_map[$project_gid]['name'] ?? ($profiles['projects'][$project_gid]['name'] ?? ('Project ' . $project_gid))));
		$profiles['projects'][$project_gid] = [
			'name' => $project_name,
			'hidden_keys' => $hidden_clean,
			'creation_mode' => $posted_creation_mode,
		];

		update_option('afb_cg_field_visibility_profiles', $profiles);
		$profiles = afb_get_client_gateway_visibility_profiles();
		if (!isset($profiles['projects']) || !is_array($profiles['projects'])) {
			$profiles['projects'] = [];
		}

		if (!isset($projects_map[$project_gid])) {
			$projects_map[$project_gid] = [
				'gid' => $project_gid,
				'name' => $project_name,
			];
		}

		$selected_project_gid = $project_gid;
		$notice_message = 'Client Gateway settings saved for this project.';
		$notice_class = 'notice-success';
	}
}

uasort($projects_map, static function ($a, $b) {
	return strcasecmp($a['name'], $b['name']);
});

$page_slug = 'afb-client-gateway-settings';
$landing_url = add_query_arg([
	'page' => $page_slug,
], admin_url('admin.php'));

$project_settings_url = static function (string $project_gid) use ($page_slug): string {
	return add_query_arg([
		'page' => $page_slug,
		'project_gid' => $project_gid,
	], admin_url('admin.php'));
};

$live_gateways_page_url = add_query_arg([
	'page' => 'afb-live-client-gateways',
], admin_url('admin.php'));

$is_project_view = $selected_project_gid !== '';
if ($is_project_view && !isset($projects_map[$selected_project_gid])) {
	$is_project_view = false;
	$selected_project_gid = '';
	$notice_message = 'Selected project was not found. Choose a project from the list below.';
	$notice_class = 'notice-warning';
}

$hard_skip_names = function_exists('afb_client_gateway_hard_skip_names')
	? afb_client_gateway_hard_skip_names()
	: ['Client Gateway PIN (SCB)'];

?>

<?php if (!$is_project_view): ?>
	<div class="wrap">
		<h1>Client Gateway Settings</h1>
		<p class="description" style="max-width:900px; margin-top: 6px;">
			Each Asana project has its own Client Gateway configuration. Select a project to open its dedicated settings page.
		</p>

		<p style="margin-top: 12px;">
			<a class="button button-secondary" href="<?= esc_url($live_gateways_page_url) ?>">Open Live Client Gateways Page</a>
		</p>

		<?php if ($notice_message !== ''): ?>
			<div class="notice <?= esc_attr($notice_class) ?> is-dismissible" style="max-width:900px; margin-top:12px;">
				<p><?= esc_html($notice_message) ?></p>
			</div>
		<?php endif; ?>

		<?php if (empty($projects_map)): ?>
			<div class="notice notice-warning" style="max-width:900px; margin-top:12px;">
				<p>No projects were found yet. Make sure at least one Asana account is active, then reload this page.</p>
			</div>
		<?php else: ?>
			<table class="widefat striped" style="max-width:1100px; margin-top: 14px;">
				<thead>
					<tr>
						<th>Project</th>
						<th style="width:210px;">Project GID</th>
						<th style="width:140px;">Fields Seen</th>
						<th style="width:140px;">Creation Mode</th>
						<th style="width:140px;">Configured</th>
						<th style="width:180px;"></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ($projects_map as $project_row): ?>
						<?php
							$gid = (string)$project_row['gid'];
							$mode = strtolower(sanitize_text_field((string)($profiles['projects'][$gid]['creation_mode'] ?? 'manual')));
							if (!in_array($mode, ['manual', 'automatic'], true)) {
								$mode = 'manual';
							}
							$field_count = count($fields_by_project[$gid] ?? []);
							$is_configured = isset($profiles['projects'][$gid]);
						?>
						<tr>
							<td>
								<a href="<?= esc_url($project_settings_url($gid)) ?>"><strong><?= esc_html($project_row['name']) ?></strong></a>
							</td>
							<td><code><?= esc_html($gid) ?></code></td>
							<td><?= esc_html((string)$field_count) ?></td>
							<td><?= esc_html(ucfirst($mode)) ?></td>
							<td><?= $is_configured ? 'Yes' : 'No' ?></td>
							<td>
								<a class="button button-secondary" href="<?= esc_url($project_settings_url($gid)) ?>">Edit Project Settings</a>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<p class="description" style="margin-top: 10px; max-width: 900px;">
				Projects are pulled from active Asana accounts and recent Client Gateway cache data.
			</p>
		<?php endif; ?>
	</div>

<?php else: ?>
	<?php
	$project_name = sanitize_text_field((string)($projects_map[$selected_project_gid]['name'] ?? ('Project ' . $selected_project_gid)));
	$project_profile = is_array($profiles['projects'][$selected_project_gid] ?? null)
		? $profiles['projects'][$selected_project_gid]
		: [];

	$project_creation_mode = strtolower(sanitize_text_field((string)($project_profile['creation_mode'] ?? 'manual')));
	if (!in_array($project_creation_mode, ['manual', 'automatic'], true)) {
		$project_creation_mode = 'manual';
	}

	$active_hidden_keys = $project_profile['hidden_keys'] ?? [];
	if (!is_array($active_hidden_keys)) {
		$active_hidden_keys = [];
	}
	$active_hidden_keys = array_values(array_unique(array_filter(array_map('sanitize_text_field', $active_hidden_keys))));

	$active_fields_map = $fields_by_project[$selected_project_gid] ?? [];
	?>

	<div class="wrap">
		<p style="margin: 6px 0 10px;"><a href="<?= esc_url($landing_url) ?>">&larr; Back to All Projects</a></p>
		<h1>Client Gateway Settings: <?= esc_html($project_name) ?></h1>
		<p class="description" style="max-width:900px; margin-top: 6px;">
			Project GID: <code><?= esc_html($selected_project_gid) ?></code>
		</p>

		<?php if ($notice_message !== ''): ?>
			<div class="notice <?= esc_attr($notice_class) ?> is-dismissible" style="max-width:900px; margin-top:12px;">
				<p><?= esc_html($notice_message) ?></p>
			</div>
		<?php endif; ?>

		<div class="notice notice-info" style="max-width:900px; margin-top: 10px;">
			<p>
				The following field is always hidden for security: <strong><?= esc_html(implode(', ', $hard_skip_names)) ?></strong>.
			</p>
		</div>

		<form method="post">
			<?php wp_nonce_field('afb_save_cg_settings'); ?>
			<input type="hidden" name="project_gid" value="<?= esc_attr($selected_project_gid) ?>" />

			<table class="form-table" style="max-width:900px; margin-top: 8px;">
				<tr>
					<th scope="row"><label for="afb-cg-creation-mode-project">Creation Mode</label></th>
					<td>
						<select id="afb-cg-creation-mode-project" name="afb_cg_creation_mode">
							<option value="manual" <?= selected($project_creation_mode, 'manual', false) ?>>Manual</option>
							<option value="automatic" <?= selected($project_creation_mode, 'automatic', false) ?>>Automatic</option>
						</select>
						<p class="description">Manual writes a Create Client Gateway link to the task. Automatic also triggers gateway creation in the background while keeping the manual link as fallback.</p>
					</td>
				</tr>
			</table>

			<?php if (empty($active_fields_map)): ?>
				<div class="notice notice-warning" style="max-width:900px;">
					<p>
						No custom fields were discovered for this project yet. Open at least one Client Gateway page for this project, then return here.
					</p>
				</div>
			<?php else: ?>
				<table class="widefat striped" style="max-width:1100px; margin-top: 12px;">
					<thead>
						<tr>
							<th style="width:70px;">Hidden</th>
							<th>Field</th>
							<th style="width:120px;">Type</th>
							<th style="width:280px;">Identifier</th>
							<th style="width:120px;">Seen In</th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ($active_fields_map as $row): ?>
							<?php
								$is_hard_hidden = in_array($row['name'], $hard_skip_names, true);
								$checked = $is_hard_hidden || in_array($row['key'], $active_hidden_keys, true);
							?>
							<tr>
								<td>
									<?php if ($is_hard_hidden): ?>
										<input type="checkbox" checked disabled />
									<?php else: ?>
										<input
											type="checkbox"
											name="afb_cg_hidden_keys[]"
											value="<?= esc_attr($row['key']) ?>"
											<?= checked($checked, true, false) ?>
										/>
									<?php endif; ?>
								</td>
								<td>
									<strong><?= esc_html($row['name']) ?></strong>
									<?php if (!empty($row['gid'])): ?>
										<div style="color:#6b7280; font-size:12px; margin-top:2px;">GID: <?= esc_html($row['gid']) ?></div>
									<?php endif; ?>
								</td>
								<td><?= esc_html($row['type'] ?: 'unknown') ?></td>
								<td><code><?= esc_html($row['key']) ?></code></td>
								<td><?= esc_html((string)$row['count']) ?> cache<?= ((int)$row['count'] === 1 ? '' : 's') ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>

			<p style="margin-top: 14px; max-width: 900px;" class="description">
				Checked means the field will be hidden from the Client Gateway Additional Details panel.
				Unchecked fields are shown.
			</p>

			<p style="margin-top: 12px;">
				<button type="submit" name="afb_save_cg_settings" class="button button-primary">Save Settings</button>
			</p>
		</form>
	</div>
<?php endif; ?>
