@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;">
<div class="loader-sec" style="display: none;">
	<div class="loader"></div>
</div>
<input type="hidden" id="memid" value="{{ $memid }}">
<main class="mainSection dashboard ">
	<div class="container-fluid px-3 px-md-4">
		<div class="prices-page">
			<div class="prices-page__content">
				<div class="forcast-tabs">
					<div class="position-relative tabs-container">
						<ul class="nav nav-tabs" id="forecast-main-tabs" role="tablist">
							<li class="nav-item" role="presentation">
								<button class="nav-link active" id="dashboard-tab" data-bs-toggle="tab" data-bs-target="#dashboard" type="button" role="tab">Dashboard</button>
							</li>
							<li class="nav-item" role="presentation">
								<button class="nav-link" id="commodity-tab" data-bs-toggle="tab" data-bs-target="#commodity" type="button" role="tab">Commodity market drives </button>
							</li>
							<li class="nav-item" role="presentation">
								<button class="nav-link" id="methodology-tab" data-bs-toggle="tab" data-bs-target="#methodology" type="button" role="tab">Methodology</button>
							</li>
						</ul>
						<div class="custom-select-button">
							<select id="productSelect" onchange="if(this.value) window.location.href=this.options[this.selectedIndex].getAttribute('data-href');">
								@foreach($subscribedProducts as $subscribedProduct)
								<option value="{{ $subscribedProduct['id'] }}"
									data-href="{{ url('forecast/product/' . $subscribedProduct['id']) }}"
									{{ $subscribedProduct['id'] == $forecastProductId ? 'selected' : '' }}>
									{{ $subscribedProduct['forecast_name'] }}
								</option>
								@endforeach
							</select>


						</div>
					</div>
					<!-- Tabs content -->
					<div class="tab-content mt-3" id="commodityTabsContent">
						<div class="tab-pane fade show active" id="dashboard" role="tabpanel">
							<ul class="nav nav-tabs inner-tabs" id="commodityTabs" role="tablist">
								<li class="nav-item" role="presentation">
									<button class="nav-link active" id="short-term-tab" data-bs-toggle="tab" data-bs-target="#short-term" type="button" role="tab">Short term</button>
								</li>
								<li class="nav-item" role="presentation">
									<button class="nav-link" id="medium-term-tab" data-bs-toggle="tab" data-bs-target="#medium-term" type="button" role="tab">Medium term</button>
								</li>
								<li class="nav-item" role="presentation">
									<button class="nav-link" id="long-term-tab" data-bs-toggle="tab" data-bs-target="#long-term" type="button" role="tab">Long term</button>
								</li>
							</ul>

							@php
							$terms = [
							'short' => 'Short Term',
							'medium' => 'Medium Term',
							'long' => 'Long Term',
							];
							@endphp

							<div class="tab-content" id="dashboardTabsContent">
								@foreach($terms as $key => $label)
								<div class="tab-pane fade @if($loop->first) show active @endif" id="{{ $key }}-term" role="tabpanel">
									<div class="terms-row">
										<div class="graph-collunm position-relative">

											<!-- Toggle icons -->
											<div class="view-toggle text-right mb-2">
												<button id="{{ $key }}ChartBtn" class="btn btn-sm btn-primary">📊 Chart</button>
												<button id="{{ $key }}TableBtn" class="btn btn-sm btn-outline-secondary">📋 Table</button>
											</div>

											<!-- Chart -->
											<div id="chart-{{ $key }}" style="height: 400px; width: 100%; max-width: 100%;"></div>

											<!-- Table (hidden by default) -->
											<div id="table-{{ $key }}" class="mt-3" style="display: none;">
												<table class="table table-bordered">
													<thead>
														<tr>
															<th>Month</th>
															<th>Spot Price</th>
															<th>Forecast Price</th>
															<th>Δ %</th>
														</tr>
													</thead>
													<tbody id="tableBody-{{ $key }}"></tbody>
												</table>
											</div>
										</div>

										<div class="content-collunm">
											<p>{!! $rationale !!}</p>
										</div>
									</div>
								</div>
								@endforeach
							</div>


						</div>
						@php
						use Illuminate\Support\Str;
						@endphp

						<div class="tab-pane fade" id="commodity" role="tabpanel">
							<ul class="nav nav-tabs inner-tabs" id="commodity-innerTabs" role="tablist">
								@foreach($categories as $index => $category)
								@php
								$slug = Str::slug($category, '-'); // convert category to slug
								@endphp
								<li class="nav-item" role="presentation">
									<button
										class="nav-link @if($index === 0) active @endif"
										id="{{ $slug }}-tab"
										data-bs-toggle="tab"
										data-bs-target="#{{ $slug }}"
										type="button"
										role="tab">
										{{ $category }}
									</button>
								</li>
								@endforeach
							</ul>

							<div class="tab-content" id="commodityInnerTabsContent">
								@foreach($marketDrivers as $index => $categoryData)
								@php
								$slug = Str::slug($categoryData['category'], '-');
								@endphp
								<div
									class="tab-pane fade @if($index === 0) show active @endif"
									id="{{ $slug }}"
									role="tabpanel">

									<div class="terms-row">
										<div class="graph-collunm">
											<div class="graph-option">
												<div class="custom-select-wrapper">
													<select name="market_driver">
														@foreach($categoryData['drivers'] as $driver)
														<option value="{{ $driver['id'] }}">
															{{ $driver['commodity_market_drivers_name'] }}
														</option>
														@endforeach
													</select>
												</div>
												<div class="compare-link">
													<a href="#">
														<input type="checkbox" name="">
														Compare with price movement
													</a>
												</div>
											</div>
											<div class="market-driver-chart" id="graph-container-{{ $slug }}" style="height: 400px; width: 100%; max-width: 100%;"></div>
										</div>
										<div class="content-collunm d-none">
											<p>{{ $categoryData['category'] }} related description goes here...</p>
											<p>It has survived not only five centuries, but also the leap into electronic typesetting.</p>
										</div>
									</div>
								</div>
								@endforeach
							</div>
						</div>


						<div class="tab-pane fade" id="methodology" role="tabpanel">
							<div class="row">
								<div class="col-md-8 methodology-content">
									<h6>Methodology</h6>
									<p>The foundation of our forecasting methodology lies in the careful selection of data that significantly influences the commodity under analysis. Data refers to both statistical data—including quantitative economic and market indicators—and news-based insights, which we monitor to conduct sentiment analysis. Together, these provide a comprehensive view of the factors influencing commodity prices.</p>
									<p>Once the key drivers are finalized, the next step is to gather relevant and credible data aligned with each driver to support accurate and robust analysis. We primarily source data from BigMint’s proprietary database, government publications, and industry association reports. These datasets are compiled and verified by our in-house team to ensure validated and up-to-date figures essential for forecast analysis.</p>
									<p>Once the relevant data is collected, the next critical step is Database Creation. This stage transforms raw, unstructured datasets into a clean, consistent, and analysis-ready format. Preprocessing addresses noise, inconsistencies, and missing values; visualization identifies patterns and outliers; and descriptive analysis extracts meaningful insights. As part of this step, we also prepare the data environment to incorporate sentiment analysis, bridging the gap between structured market data and qualitative news insights.</p>
									<p>With a clean, structured, and enriched dataset in place—including both statistical drivers and sentiment-derived inputs—the next phase focuses on deriving actionable forecasts. Feature engineering strengthens the model’s ability to detect trends and cycles, while model selection identifies the most suitable forecasting algorithms. NeuralForecast models capture complex non-linear relationships, StatsForecast models offer transparency, and tree-based regression models flexibly incorporate engineered covariates, including sentiment scores.</p>
									<div class="table-responsive">
										<table class="forecast-table table table-bordered methodology-table">
											<thead>
												<tr>
													<th><b>Metrics</b></th>
													<th><b>Evaluation Metrics Value</b></th>
													<th><b>Billet Raipur</b></th>
													<th><b>HR Plate Mumbai</b></th>
													<th><b>Rebar IF Route Mumbai</b></th>
													<th><b>Chhattisgarh Fines</b></th>
													<th><b>Odisha Index</b></th>
													<th><b>Pellet</b></th>
													<th><b>Rebar BF Route Mumbai</b></th>
													<th><b>Rebar IF Route Raipur</b></th>
													<th><b>Wire Rod Raipur</b></th>
													<th><b>CRC</b></th>
													<th><b>GP</b></th>
													<th><b>GI</b></th>
													<th><b>HMS 80:20 Turkey</b></th>
													<th><b>HMS 80:20 Mumbai2</b></th>
												</tr>
											</thead>
											<tbody>
												<tr>
													<td>Accuracy Range 1M</td>
													<td>High price-level accuracy Min 95%</td>
													<td>>95%</td>
													<td>>98%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>95%</td>
													<td>>98%</td>
													<td>>98%</td>
													<td>>98%</td>
													<td>>98%</td>
													<td>>98%</td>
												</tr>
												<tr>
													<td>Accuracy Range 2M,3M</td>
													<td>High price-level accuracy Min 95%</td>
													<td>>92%</td>
													<td>>96%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>92%</td>
													<td>>96%</td>
													<td>>96%</td>
													<td>>96%</td>
													<td>>96%</td>
												</tr>
												<tr>
													<td>Delta Range in % </td>
													<td>2 to 3 %</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±3%</td>
													<td>±2%</td>
													<td>±4%</td>
												</tr>
												<tr>
													<td>Mean Absolute Percentage Error (MAPE)</td>
													<td>MAPE ≤ 2%, which is typically acceptable</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈2%</td>
													<td>≈0.61%</td>
													<td>≈0.61%</td>
													<td>≈0.70%</td>
													<td>≈2%</td>
													<td>≈2%</td>
												</tr>
											</tbody>
										</table>
									</div>
									<p>The final step is forecast validation. The evaluation process follows a robust out-of-sample validation approach, where the most recent portion of the dataset is held out as a test set. Standard metrics such as RMSE and MAPE are computed, complemented by visual inspection of predicted versus actual prices. If evaluation results are unsatisfactory, the model development loop is revisited with alternative feature sets, model architectures, or ensemble strategies. Once validated, forecasts are translated into intuitive, decision-friendly formats to communicate projected trends and drivers to stakeholders.</p>
								</div>
								<div class="col-md-4">
									<img src="{{ url('public/bm/new-images/forecast-triangle.jpg') }}" alt="My Image">
								</div>
							</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>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
	function toggleLoader(show) {
		const loader = document.querySelector('.loader-sec');
		if (show) {
			loader.style.display = 'block';
		} else {
			loader.style.display = 'none';
		}
	}
	const loadedCharts = {};
	const charts = {}; // store chart instances
	const chartData = {}; // store API data for table rendering
	const forecastProductId = @json($forecastProductId);

	function loadChart(term, containerId, tableBodyId) {
		if (loadedCharts[term]) return;

		const container = document.getElementById(containerId);

		// show loader before sending request
		toggleLoader(true);


		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: "dashboard_summary",
					forecast_product_id: forecastProductId,
					term: term
				})
			})
			.then(res => res.json())
			.then(data => {
				// save API data for table view
				chartData[term] = data;

				// init chart
				charts[term] = Highcharts.chart(containerId, {
					credits: {
						enabled: true,
						text: 'bigmint.co',
						href: 'https://www.bigmint.co/'
					},
					chart: {
						type: "line"
					},
					title: {
						text: "Spot vs Forecast Prices (" + term + ")"
					},
					xAxis: {
						categories: data.categories
					},
					yAxis: {
						title: {
							text: "Values"
						}
					},
					series: [{
							name: "Spot Price",
							data: data.spot,
							color: "#1e62b9"
						},
						{
							name: "Forecast Price",
							data: data.forecast,
							dashStyle: "Dash",
							color: "#ff0000",
							tooltip: {
								pointFormatter: function() {
									const i = this.index;
									const min = data.forecast_min[i];
									const max = data.forecast_max[i];
									const forecast = this.y;

									return `
										<div style="
											padding: 10px; 
											font-family: Arial, sans-serif; 
											background: rgba(255,255,255,0.95); 
											border-radius: 6px; 
											box-shadow: 0 2px 8px rgba(0,0,0,0.3);
											text-align: center;
											min-width: 100px;
										">
											<div style="font-weight: bold; color: #1e62b9; margin-bottom: 5px;">Max: ${max}</div><br>
											<div style="font-weight: bold; color: #ff0000; margin-bottom: 5px;">Forecast: ${forecast}</div><br>
											<div style="font-weight: bold; color: #1e62b9;">Min: ${min}</div>
										</div>
									`;
								}
							}
						}
					]
				});

				loadedCharts[term] = true;

				// attach toggle handlers
				setupToggles(term, containerId, tableBodyId);
			})
			.catch(err => {
				container.innerHTML = `<p style="color:red;text-align:center;">Error loading chart</p>`;
				console.error("Error loading chart:", err);
			})
			.finally(() => {
				toggleLoader(false);
			});
	}

	function renderTable(data, tableBodyId) {
		const tbody = document.getElementById(tableBodyId);
		tbody.innerHTML = "";

		data.categories.forEach((month, i) => {
			const spot = data.spot[i] ?? "-";
			const forecast = data.forecast[i] ?? "-";
			const delta =
				data.delta && data.delta[i] !== null && data.delta[i] !== undefined ?
				data.delta[i] + "%" :
				"-";

			const row = `
			<tr>
				<td>${month}</td>
				<td>${spot}</td>
				<td>${forecast}</td>
				<td>${delta}</td>
			</tr>
		`;
			tbody.insertAdjacentHTML("beforeend", row);
		});
	}

	function setupToggles(term, chartId, tableBodyId) {
		// Chart button
		document.getElementById(term + "ChartBtn").addEventListener("click", () => {
			document.getElementById(chartId).style.display = "block";
			document.getElementById("table-" + term).style.display = "none";
		});

		// Table button
		document.getElementById(term + "TableBtn").addEventListener("click", () => {
			if (chartData[term]) {
				renderTable(chartData[term], tableBodyId);
			}
			document.getElementById(chartId).style.display = "none";
			document.getElementById("table-" + term).style.display = "block";
		});
	}

	// Default load short-term
	document.addEventListener("DOMContentLoaded", function() {
		loadChart("short", "chart-short", "tableBody-short");
	});

	// Handle tab change
	document.querySelectorAll('#commodityTabs button[data-bs-toggle="tab"]').forEach(tab => {
		tab.addEventListener("shown.bs.tab", function(e) {
			const targetId = e.target.getAttribute("data-bs-target"); // #short-term / #medium-term / #long-term
			let term = "";
			let containerId = "";
			let tableBodyId = "";

			if (targetId === "#short-term") {
				term = "short";
				containerId = "chart-short";
				tableBodyId = "tableBody-short";
			} else if (targetId === "#medium-term") {
				term = "medium";
				containerId = "chart-medium";
				tableBodyId = "tableBody-medium";
			} else if (targetId === "#long-term") {
				term = "long";
				containerId = "chart-long";
				tableBodyId = "tableBody-long";
			}

			loadChart(term, containerId, tableBodyId);
		});
	});




	// Global cache for market driver responses
	const marketDriverCache = {};

	document.addEventListener("DOMContentLoaded", function() {
		// Bootstrap event when a tab is shown
		document.querySelectorAll('#commodity-innerTabs button[data-bs-toggle="tab"]').forEach(tabBtn => {
			tabBtn.addEventListener("shown.bs.tab", function(e) {
				let targetId = e.target.getAttribute("data-bs-target");
				if (!targetId) return;

				let activePane = document.querySelector(targetId);
				if (!activePane) return;

				loadMarketDrivers(activePane);
			});
		});

		// Load the first tab on page load
		let firstTabBtn = document.querySelector('#commodity-innerTabs button[data-bs-toggle="tab"]');
		if (firstTabBtn) {
			let firstTargetId = firstTabBtn.getAttribute("data-bs-target");
			let firstPane = document.querySelector(firstTargetId);
			if (firstPane) {
				loadMarketDrivers(firstPane);
			}
		}

		// on change of select box
		document.querySelectorAll("select[name='market_driver']").forEach(selectBox => {
			selectBox.addEventListener("change", function() {
				let parentPane = selectBox.closest(".tab-pane");
				if (parentPane) {
					loadMarketDrivers(parentPane);
				}
			});
		});
	});

	function loadMarketDrivers(activePane) {
		console.log("Loading market drivers for:", activePane.id);

		let selectBox = activePane.querySelector("select[name='market_driver']");
		if (!selectBox) return;

		let selectedValue = selectBox.value;
		if (!selectedValue) {
			console.warn("No market driver selected in active tab.");
			return;
		}

		let slug = activePane.id;
		let memid = document.getElementById("memid").value || "155144";

		// ✅ Check if cached data exists
		if (marketDriverCache[selectedValue]) {
			console.log("Using cached data for market_driver_id:", selectedValue);
			makeMarketDriversChart(slug, marketDriverCache[selectedValue]);
			return;
		}

		// show loader before sending request
		toggleLoader(true);

		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: "comodity_market_drivers_chart",
					forecast_product_id: forecastProductId,
					market_driver_id: selectedValue,
					memid: memid
				})
			})
			.then(res => res.json())
			.then(data => {
				if (data.status === "success") {
					// ✅ Save to cache
					marketDriverCache[selectedValue] = data;
					makeMarketDriversChart(slug, data);
				} else {
					console.error("API error:", data.message);
				}
			})
			.catch(err => console.error("Error loading chart:", err))

			.finally(() => {
				toggleLoader(false);
			});
	}

	function makeMarketDriversChart(slug, data) {
		const categories = data.categories || [];
		const costOfProduction = data.cost_of_production || [];
		const spotPrice = data.spot || [];
		const forecastPrice = data.forecast || [];
		const chartType = data.graph_type || "line";
		const forecastProduct = data.forecast_product || "";
		const marketDriver = data.market_driver || "";
		const currency = data.currency || "";
		const driverUnit = data.driver_unit || "";

		const isBar = chartType === "bar";

		const chart = Highcharts.chart("graph-container-" + slug, {
			credits: {
				enabled: true,
				text: "bigmint.co",
				href: "https://www.bigmint.co/"
			},
			chart: {
				type: isBar ? "column" : "line"
			},
			title: {
				text: "Cost of Production vs Spot vs Forecast"
			},
			xAxis: {
				categories: categories
			},
			yAxis: [{
					// Left axis
					title: {
						text: (isBar ? "Quantity in " : "Prices in ") + (driverUnit || "Unit")
					}
				},
				{
					// Right axis (always prices in currency)
					title: {
						text: "Prices in " + (currency || "INR")
					},
					opposite: true
				}
			],
			tooltip: {
				shared: true,
				valueDecimals: 2
			},
			series: [{
				name: marketDriver,
				data: costOfProduction,
				color: "#1e62b9",
				type: isBar ? "column" : "line",
				yAxis: isBar ? 0 : undefined // bind to left axis if bar
			}]
		});

		const checkbox = document.querySelector(
			`#${slug} .graph-option input[type="checkbox"]`
		);
		if (checkbox) {
			checkbox.addEventListener("change", function() {
				if (this.checked) {
					chart.addSeries({
						name: forecastProduct + " - Spot Price",
						data: spotPrice,
						color: "#ff0000",
						type: "line",
						yAxis: isBar ? 1 : 0 // bind to right axis if bar
					});
					chart.addSeries({
						name: forecastProduct + " - Forecast Price",
						data: forecastPrice,
						color: "#ff0000",
						dashStyle: "Dash",
						type: "line",
						yAxis: isBar ? 1 : 0
					});
				} else {
					// Match correct names and remove
					const toRemove = chart.series.filter(
						(s) =>
						s.name === forecastProduct + " - Spot Price" ||
						s.name === forecastProduct + " - Forecast Price"
					);
					toRemove.forEach((s) => s.remove());
				}
			});
		}
	}
</script>

@endsection('content')