<?php
if (!defined('ABSPATH')) {
	exit;
}

if (!is_user_logged_in()) {
	echo "<div class='alert alert-warning'>Please login to view documentation.</div>";
	return;
}

$user_id = get_current_user_id();
global $wpdb;
$vp_user = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}vtupress_users WHERE userId = %d", $user_id));
$apikey = $vp_user ? $vp_user->apikey : 'Not Generated';

$base_url = home_url('/api/');
?>

<div class="container-fluid mt-4">
	<div class="row mb-4">
		<div class="col-12">
			<div class="card bg-secondary-gradient text-white">
				<div class="card-body">
					<h2 class="text-white"><i class="mdi mdi-api mr-2"></i> Developer Documentation</h2>
					<p class="mb-0">Integrate our services into your application using our robust API.</p>
				</div>
			</div>
		</div>
	</div>

	<!-- Authentication -->
	<div class="row mb-4">
		<div class="col-md-6">
			<div class="card h-100">
				<div class="card-header font-weight-bold">Authentication</div>
				<div class="card-body">
					<p>Authenticate your requests by including your API Key in the <strong>Header</strong>.</p>
					<div class="alert alert-secondary">
						<strong>Header:</strong><br>
						<code>Authorization: Bearer <?= esc_attr($apikey) ?></code>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-6">
			<div class="card h-100">
				<div class="card-header font-weight-bold">Base Configuration</div>
				<div class="card-body">
					<p><strong>Base URL:</strong> <code><?= $base_url ?></code></p>
					<p><strong>Method:</strong> <code>GET</code> or <code>POST</code></p>
					<p><strong>Response Format:</strong> <code>JSON</code></p>
					<div class="form-group mb-0">
						<label class="font-weight-bold">Your API Key</label>
						<div class="input-group">
							<input type="text" class="form-control" value="<?= esc_attr($apikey) ?>" readonly
								id="apiKeyField">
							<div class="input-group-append">
								<button class="btn btn-outline-secondary" type="button"
									onclick="copyToClipboard('apiKeyField')">Copy</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Services -->
	<div class="row">
		<div class="col-12">
			<h3 class="mb-3">Services Endpoints</h3>
			<div class="accordion" id="apiAccordion">
				<?php
				$services = Vtupress_Service_Container::all(true);

				function get_internal_pins_doc($type)
				{
					global $wpdb;
					$table = $wpdb->prefix . 'vtupress_internal_pins';
					// Group by name, value as requested to show unique plans
					// Provider is ID, Plan is Value
					return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE service_id = %s GROUP BY plan_id, value, price", $type), ARRAY_A);
				}

				function get_standard_plans_doc($service_id)
				{
					global $wpdb;
					$table = $wpdb->prefix . 'vtupress_servicePlans';
					return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE service_name = %s ORDER BY listOrder ASC", $service_id), ARRAY_A);
				}


				foreach ($services as $service):
					// Exclude Transfer and Withdrawal services
					if (strpos(strtolower($service->id), 'transfer') !== false || strpos(strtolower($service->id), 'withdrawal') !== false) {
						continue;
					}

					$endpoint = $base_url . $service->id;
					$payloads = $service->payload ?? [];
					// Remove apikey from payload list as it's in header now
					$payloads = array_diff($payloads, ['apikey']);

					$is_voucher = property_exists($service, 'is_voucher') && $service->is_voucher;
					?>
					<div class="card mb-3">
						<div class="card-header" id="heading<?= $service->id ?>">
							<h5 class="mb-0">
								<button
									class="btn btn-link btn-block text-left font-weight-bold text-dark text-decoration-none"
									type="button" data-toggle="collapse" data-target="#collapse<?= $service->id ?>"
									aria-expanded="true" aria-controls="collapse<?= $service->id ?>">
									<i class="<?= $service->icon ?> mr-2"></i> <?= ucfirst($service->name) ?>
									<span class="badge badge-info float-right">/<?= $service->id ?></span>
								</button>
							</h5>
						</div>

						<div id="collapse<?= $service->id ?>" class="collapse" aria-labelledby="heading<?= $service->id ?>"
							data-parent="#apiAccordion">
							<div class="card-body">
								<p><strong>Endpoint:</strong> <code><?= $endpoint ?></code></p>

								<!-- Payload Table -->
								<h6 class="mt-4">Required Parameters</h6>
								<table class="table table-bordered table-striped">
									<thead class="thead-light">
										<tr>
											<th>Parameter</th>
											<th>Description</th>
											<th>Example/Values</th>
										</tr>
									</thead>
									<tbody>
										<?php foreach ($payloads as $field):
											$desc = "Required Field";
											$example = "-";

											if ($field === 'provider') {
												$desc = $is_voucher ? "ID of the Provider" : "Network/Provider Code";
												$example = $is_voucher ? "See 'ID' below" : "See codes below";
											} elseif ($field === 'plan') {
												$desc = $is_voucher ? "Value of the pin (Amount)" : "Plan ID";
												$example = $is_voucher ? "100, 200, 500" : "Auto-generated ID";
											} elseif ($field === 'amount') {
												$desc = "Amount to transaction";
												$example = "100";
											} elseif ($field === 'phone' || $field === 'recipient') {
												$desc = "Recipient identifier";
												$example = "08012345678";
											} elseif ($field === 'quantity') {
												$desc = "Number of items";
												$example = "1";
											} elseif ($field === 'type') {
												$desc = "Service Type";
												$example = implode(', ', $service->service_types ?? []);
											}
											?>
											<tr>
												<td><code><?= $field ?></code></td>
												<td><?= $desc ?></td>
												<td><?= $example ?></td>
											</tr>
										<?php endforeach; ?>
									</tbody>
								</table>

								<!-- Plans/Providers Table -->
								<?php if ($is_voucher):
									$pin_type = '';
									if ($service->id == 'recharge_card')
										$pin_type = 'airtime';
									elseif ($service->id == 'data_card')
										$pin_type = 'data';
									elseif ($service->id == 'exam_pin')
										$pin_type = 'exam';

									$pins = $service->id ? get_internal_pins_doc($service->id) : [];
									?>
									<h6 class="mt-4">Available Providers & Values</h6>
									<?php if ($pins): ?>
										<table class="table table-sm table-responsive-sm">
											<thead>
												<tr>
													<th>ID (use as provider)</th>
													<th>Plan (use as plan)</th>
													<th>Price</th>
												</tr>
											</thead>
											<tbody>
												<?php
												foreach ($pins as $p) {
													?>
													<tr>
														<td><?= $p['plan_id'] ?></td>
														<td><?= esc_html($p['value']) ?></td>
														<td>₦<?= esc_html($p['price']) ?></td>
													</tr>
												<?php } ?>
											</tbody>
										</table>
									<?php else: ?>
										<p class="text-muted">No configuration found.</p>
									<?php endif; ?>

								<?php elseif ($service->id === 'airtime' || $service->id === 'data' || $service->id === 'cable' || $service->id === 'bill'):
									// Standard Plans
									$plans = get_standard_plans_doc($service->id);
									?>
									<h6 class="mt-4">Available Plans</h6>
									<?php if ($plans): ?>
										<table class="table table-sm table-responsive-sm">
											<thead>
												<tr>
													<th>Plan ID</th>
													<th>Map</th>
													<th>Type</th>
													<th>User Price</th>
												</tr>
											</thead>
											<tbody>
												<?php foreach ($plans as $p):
													$net = strtolower($p['network'] ?? '');
													$type = strtolower($p['service_type'] ?? 'subscription');
													$map = $net . "_" . $type;

													// Construct Composite Plan ID
													// {network}_{service_type}_{duration_figure}_{duration_time}_{prefix}_{surfix}
													$dur_fig = $p['duration_figure'] ?? '0';
													$dur_time = strtolower($p['duration_time'] ?? 'null');
													$prefix = strtolower($p['prefix'] ?? 'null');
													$surfix = strtolower($p['surfix'] ?? 'null');

													// Handle empty values gracefully to match user expectation format
													// If any are missing, default to empty string or identifiable placeholder if strict
									
													$composite_id = "{$net}_{$type}_{$dur_fig}_{$dur_time}_{$prefix}_{$surfix}";
													?>
													<tr>
														<td><?= esc_html($composite_id) ?></td>
														<td><?= esc_html($map) ?></td>
														<td><?= esc_html($p['service_type']) ?></td>
														<td>₦<?= esc_html($p['plan_price']) ?></td>
													</tr>
												<?php endforeach; ?>
											</tbody>
										</table>
									<?php else: ?>
										<p class="text-muted">No plans configured.</p>
									<?php endif; ?>

								<?php endif; ?>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
	</div>
</div>

<script>
	function copyToClipboard(elementId) {
		var copyText = document.getElementById(elementId);
		copyText.select();
		copyText.setSelectionRange(0, 99999);
		navigator.clipboard.writeText(copyText.value).then(function () {
			alert("Copied to clipboard!");
		});
	}
</script>