@extends('layouts.fixed-steelmint')
@section('content')
<link rel="stylesheet" href="{{ url('/assets/css/forecast.css') }}?v={{ time() }}">
<input type="text" id="api-endpoint" value="{{ $apiEndpoint }}" style="display:none;">
<input type="hidden" id="memid" value="{{steelAuth::getID()}}">
<main class="mainSection dashboard ">
	<div class="container-fluid px-3 px-md-4">
		@if(session('error'))
		<div class="alert alert-danger">
			{{ session('error') }}
		</div>
		@endif
		<div class="prices-page">
			<div class="prices-page__content">
				<div class="forcast-tabs">
					<ul class="nav nav-tabs" id="commodityTabs" role="tablist">
						<li class="nav-item" role="presentation">
							<button class="nav-link active" id="forecast-tab" data-bs-toggle="tab" data-bs-target="#forecast" type="button" role="tab">Forecast Commodities</button>
						</li>
						<li class="nav-item" role="presentation">
							<button class="nav-link" id="watchlist-tab" data-bs-toggle="tab" data-bs-target="#watchlist" type="button" role="tab">My Watchlist</button>
						</li>
					</ul>
					<!-- Tabs content -->
					<div class="tab-content mt-3" id="commodityTabsContent">
						<div class="tab-pane fade show active" id="forecast" role="tabpanel">
							@php
							$markets = [
							['key' => 'ferrous', 'label' => 'Ferrous'],
							['key' => 'scrap-recycling', 'label' => 'Scrap & Recycling'],
							['key' => 'coal', 'label' => 'Coal & Energy'],
							['key' => 'non-ferrous', 'label' => 'Non Ferrous'],
							['key' => 'agriculture', 'label' => 'Agriculture'],
							];
							@endphp

							<div class="row">
								@foreach($markets as $market)
								<div class="col-lg-6 col-md-12 mb-4">
									<div class="section-title">{{ $market['label'] }}</div>
									<div class="table-responsive">
										<table class="forecast-table table table-bordered">
											<thead>
												<tr>
													<th rowspan="2"><b>Product</b></th>
													<th colspan="2"><b>Short term</b></th>
													<th colspan="2"><b>Mid term</b></th>
													<th colspan="2"><b>Long term</b></th>
												</tr>
												<tr>
													<th>Monthly</th>
													<th>Updated on</th>
													<th>Quarterly</th>
													<th>Updated on</th>
													<th>Yearly</th>
													<th>Updated on</th>
												</tr>
											</thead>
											<tbody id="{{ $market['key'] }}-body">
												<tr>
													<td colspan="7" class="text-center">Loading data...</td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
								@endforeach
							</div>

						</div>

						<div class="tab-pane fade" id="watchlist" role="tabpanel">
							<div class="table-responsive">
								<table class="forecast-table table table-bordered watchlist-table">
									@php
									use Carbon\Carbon;

									$now = Carbon::now();

									// Short term → next 3 months
									$shortMonths = [];
									for ($i = 1; $i <= 3; $i++) {
										$shortMonths[]=$now->copy()->addMonths($i)->format('F'); // Full month name
										}

										// Determine FY year (Indian FY → Apr–Mar)
										// If current month >= April, FY base year is current year, else previous year
										$fyBaseYear = $now->month >= 4 ? $now->year : $now->year - 1;

										// Find financial quarter
										$month = $now->month;

										// Shift months so April = 1, May = 2, …, Mar = 12
										$shiftedMonth = ($month - 4 + 12) % 12 + 1;
										$quarterNum = ceil($shiftedMonth / 3);

										// Example: "Q1FY25"
										$quarter = 'Q' . $quarterNum . 'FY' . (($fyBaseYear + 1) % 100);

										// Half year (Apr–Sep = HY1, Oct–Mar = HY2)
										$half = ($quarterNum <= 2 ? 'H1' : 'H2' ) . 'FY' . (($fyBaseYear + 1) % 100);

											// Long term → next FY (Apr–Mar)
											$long='FY' . (($fyBaseYear + 2) % 100);
											@endphp

											<thead class="table-light">
											<tr>
												<th rowspan="2"><b>Product</b></th>
												<th rowspan="2"><b>Currency</b></th>
												<th rowspan="2"><b>Spot price</b></th>
												<th rowspan="2"><b>As on</b></th>
												<th rowspan="2"><b>Forecasts</b></th>

												<th colspan="{{ count($shortMonths) + 1 }}"><b>Short term</b></th>
												<th colspan="3"><b>Medium term</b></th>
												<th colspan="2"><b>Long term</b></th>
											</tr>
											<tr>
												{{-- Short term labels --}}
												@foreach($shortMonths as $m)
												<th><b>{{ $m }}</b></th>
												@endforeach
												<th><b>Updated on</b></th>

												{{-- Medium term --}}
												<th><b>{{ $quarter }}</b></th>
												<th><b>{{ $half }}</b></th>
												<th><b>Updated on</b></th>

												{{-- Long term --}}
												<th><b>{{ $long }}</b></th>
												<th><b>Updated on</b></th>
											</tr>
											</thead>
											<tbody>
											</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
				<div class="bottom-content">
					<h6>Disclaimer:</h6>
					<p>BigMint has prepared this information with care and provides it for general reference only. It should not be used as the sole basis for trading, investment, or other critical decisions. The views expressed may come from various contributors and do not necessarily represent those of BigMint or its management.</p>
					<p>BigMint, including its employees, directors, and aliates, is not responsible for any losses, damages, or actions resulting from the use or reliance on this information. Price forecasts are generated using a defined methodology based on selected factors from available data. Some relevant factors may not be included due to data availability or suitability, and the model does not account for unexpected events, market disruptions, or sentiment-driven changes</p>
					<p>Users should keep these limitations in mind when interpreting the forecasts.</p>
				</div>
			</div>
		</div>
	</div>
</main>
{{-- Pass PHP markets array to JS --}}
<script>
	const markets = @json($markets);
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
	const el = document.getElementById('memid');
	const isLoggedIn = el && el.value.trim() !== '';
	const baseUrl = "{{ url('forecast/product') }}";

	function setLoader(id) {
		document.getElementById(id).innerHTML = `<tr><td colspan="7" class="text-center">Loading...</td></tr>`;
	}

	function showError(id) {
		document.getElementById(id).innerHTML = `<tr><td colspan="7" class="text-center text-danger">Error loading data</td></tr>`;
	}

	async function loadForecastData() {
		// Set loaders for all markets
		markets.forEach(market => setLoader(`${market.key}-body`));

		const apiEndpoint = document.getElementById("api-endpoint").value || "http://localhost:1010/api.php";

		try {
			const response = await fetch(apiEndpoint, {
				method: "POST",
				headers: {
					"Content-Type": "application/json"
				},
				body: JSON.stringify({
					action: "get_forecast_terms"
				}),
			});

			const result = await response.json();

			if (result.status !== "success") {
				markets.forEach(market => showError(`${market.key}-body`));
				return;
			}

			// Render each market dynamically
			markets.forEach(market => {
				const apiData = result.data[market.key];
				/* if (apiData) {
					renderMarket(apiData, `${market.key}-body`);
				} else {
					showError(`${market.key}-body`);
				} */
				renderMarket(apiData, `${market.key}-body`);
			});

		} catch (err) {
			console.error(err);
			markets.forEach(market => showError(`${market.key}-body`));
		}
	}


	// render one market
	function renderMarket(items, tbodyId) {
		const tbody = document.getElementById(tbodyId);
		if (!items || items.length === 0) {
			tbody.innerHTML = `<tr><td colspan="7" class="text-center text-danger">No data available</td></tr>`;
			return;
		}

		let rows = "";
		items.forEach(item => {
			const href = isLoggedIn ?
				`${baseUrl}/${item.product_id}` :
				"javascript:void(0)";

			const linkClass = isLoggedIn ? "" : "openloginBox";
			rows += `
      <tr>
        <td class="product-col"><a class="${linkClass}" href="${href}">${item.product}</a></td>
        <td>${renderTrend(item.short_term)}</td>
        <td>${formatDate(item.short_term_updated_on)}</td>
        <td>${renderTrend(item.medium_term)}</td>
        <td>${formatDate(item.medium_term_updated_on)}</td>
        <td>${renderTrend(item.long_term)}</td>
        <td>${formatDate(item.long_term_updated_on)}</td>
      </tr>
    `;
		});
		tbody.innerHTML = rows;
	}

	// helpers
	function renderTrend(val) {
		if (val === "up") return `<span class="triangle up">▲</span>`;
		if (val === "down") return `<span class="triangle down">▼</span>`;
		return "—";
	}

	function formatDate(dateStr) {
		if (!dateStr) return "—";
		const d = new Date(dateStr);
		return d.toLocaleDateString("en-GB", {
			day: "2-digit",
			month: "short",
			year: "2-digit"
		});
	}

	function showError(tbodyId) {
		document.getElementById(tbodyId).innerHTML = `<tr><td colspan="7" class="text-center text-danger">Error loading data</td></tr>`;
	}

	// call once
	loadForecastData();


	// now will get watchlist data

	document.addEventListener("DOMContentLoaded", function() {
		let watchlistLoaded = false; // ensure API called only once

		document.getElementById("watchlist-tab").addEventListener("shown.bs.tab", function() {
			if (!watchlistLoaded) {
				loadWatchlist();
				watchlistLoaded = true; // mark as loaded
			}
		});
	})

	function loadWatchlist() {

		// get memid to check login
		let memEl = document.getElementById('memid');
		let memid = memEl ? memEl.value.trim() : '';
		const isLoggedIn = memid !== '';


		// If not logged in, show message and return
		if (!isLoggedIn) {
			const tbody = document.querySelector(".watchlist-table tbody");
			tbody.innerHTML = `<tr><td colspan="13" class="text-center">Please <a href="javascript:void(0)" class="openloginBox">login</a> to view your watchlist.</td></tr>`;
			return;
		}
		const apiEndpoint = document.getElementById("api-endpoint").value || "http://localhost:1010/api.php";

		fetch(apiEndpoint, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "get_watchlist",
					user_id: memid
				})
			})
			.then(response => response.json())
			.then(res => {
				if (res.status === "success" && Array.isArray(res.data)) {
					if (res.data.length > 0) {
						// Update table headers with dynamic labels
                    	updateTableHeaders(res.labels);
						// Populate table with data
						populateWatchlistTable(res.data);
					} else {
						const tbody = document.querySelector(".watchlist-table tbody");
						tbody.innerHTML = `<tr><td colspan="13" class="text-center">You have nothing in your watchlist.</td></tr>`;
					}
				} else {
					console.error("Invalid response", res);
					const tbody = document.querySelector(".watchlist-table tbody");
					tbody.innerHTML = `<tr><td colspan="13" class="text-center">Error loading watchlist. Please try again later.</td></tr>`;
				}
			})
			.catch(err => {
				console.error("API Error:", err);
				const tbody = document.querySelector(".watchlist-table tbody");
				tbody.innerHTML = `<tr><td colspan="13" class="text-center">Something went wrong. Please try again later.</td></tr>`;
			});
	}

	function updateTableHeaders(labels) {
		const thead = document.querySelector(".watchlist-table thead");

		const shortTermCount = labels.short_term ? labels.short_term.length : 0;
		const mediumTermCount = labels.medium_term ? labels.medium_term.length : 0;

		// Calculate total columns
		const shortTermCols = shortTermCount + 1; // +1 for "Updated on"
		const mediumTermCols = mediumTermCount + 1; // +1 for "Updated on"
		const longTermCols = 2; // Label + "Updated on"

		const totalCols = 5 + shortTermCols + mediumTermCols + longTermCols;

		thead.innerHTML = `
        <tr>
            <th rowspan="2"><b>Product</b></th>
            <th rowspan="2"><b>Currency</b></th>
            <th rowspan="2"><b>Spot price</b></th>
            <th rowspan="2"><b>As on</b></th>
            <th rowspan="2"><b>Forecasts</b></th>
            <th colspan="${shortTermCols}"><b>Short term</b></th>
            <th colspan="${mediumTermCols}"><b>Medium term</b></th>
            <th colspan="${longTermCols}"><b>Long term</b></th>
        </tr>
        <tr>
            ${labels.short_term ? labels.short_term.map(month => `<th><b>${month}</b></th>`).join('') : ''}
            <th><b>Updated on</b></th>
            
            ${labels.medium_term ? labels.medium_term.map(term => `<th><b>${term}</b></th>`).join('') : ''}
            <th><b>Updated on</b></th>
            
            <th><b>${labels.long_term || 'FY'}</b></th>
            <th><b>Updated on</b></th>
        </tr>
    `;
	}

	function populateWatchlistTable(data) {
		const tbody = document.querySelector(".watchlist-table tbody");
		tbody.innerHTML = "";

		data.forEach(item => {
			const tr = document.createElement("tr");
			const href = isLoggedIn ?
				`${baseUrl}/${item.product_id}` :
				"javascript:void(0)";

			const linkClass = isLoggedIn ? "" : "openloginBox";

			tr.innerHTML = `
            <td class="product-col"><a class="${linkClass}" href="${href}">${item.product}</a></td>
            <td>${item.currency}</td>
            <td><b>${item.spot_price}</b></td>
            <td>${item.as_on}</td>
            <td class="text-left">
                <div class="bold">New</div>
				<div>Previous</div>
				<div>% Change</div>
            </td>
        `;

			// --- Short term ---
			let shortTermCols = "";
			if (item.short_term?.length) {
				item.short_term.forEach(st => {
					shortTermCols += `
                    <td>
						<span class="bold">${st.new ?? "-"}</span><br>
                        ${st.previous ?? "-"}<br>
                        ${formatChange(st.change)}
                    </td>
                `;
				});
			}
			while ((shortTermCols.match(/<td>/g) || []).length < 3) {
				shortTermCols += `<td>-</td>`;
			}
			shortTermCols += `<td>${item.short_term_updated_on || "-"}</td>`;

			// --- Medium term ---
			let mediumTermCols = "";
			if (item.medium_term?.length) {
				item.medium_term.forEach(mt => {
					mediumTermCols += `
                    <td>
                        ${mt.new ?? "-"}<br>
                        <span class="text-muted">${mt.previous ?? "-"}</span><br>
                        ${formatChange(mt.change)}
                    </td>
                `;
				});
			}
			while ((mediumTermCols.match(/<td>/g) || []).length < 2) {
				mediumTermCols += `<td>-</td>`;
			}
			mediumTermCols += `<td>${item.medium_term_updated_on || "-"}</td>`;

			// --- Long term ---
			let longTermCols = "";
			if (item.long_term?.length) {
				item.long_term.forEach(lt => {
					longTermCols += `
                    <td>
                        ${lt.new ?? "-"}<br>
                        <span class="text-muted">${lt.previous ?? "-"}</span><br>
                        ${formatChange(lt.change)}
                    </td>
                    <td>${item.long_term_updated_on || "-"}</td>
                `;
				});
			} else {
				longTermCols = `<td>-</td><td>${item.long_term_updated_on || "-"}</td>`;
			}

			tr.innerHTML += shortTermCols + mediumTermCols + longTermCols;
			tbody.appendChild(tr);
		});
	}

	function formatChange(change) {
		if (change === null || change === undefined) return `<span class="text-muted">-</span>`;
		if (change > 0) {
			return `<span class="text-success">▲ ${change}%</span>`;
		} else if (change < 0) {
			return `<span class="text-danger">▼ ${Math.abs(change)}%</span>`;
		} else {
			return `<span class="text-muted">0%</span>`;
		}
	}
</script>
@endsection('content')