<?php

namespace App\Http\Controllers;

use App\Models\DataList;
use App\Models\Master;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        // Fetch the distinct stations
        $stations = Master::select('mn')->distinct()->get();

        // Get the selected station or default to the latest station
        $selectedStation = $request->get('station', Master::latest('data_time')->first()->mn);

        // Fetch the latest data for the selected station
        $latestMaster = Master::where('mn', $selectedStation)
            ->latest('data_time')
            ->first();

        if (!$latestMaster) {
            return redirect()->back()->with('device_not_found', true);
        }

        // Fetch the latest data list for the master with the join to the codes table and sorting by the order_by column
        $latestDataList = DataList::where('master_id', $latestMaster->id)
            ->join('codes', 'data_lists.code_id', '=', 'codes.id')  // Join the codes table
            ->orderBy('codes.order_by', 'asc')  // Sort by the 'order_by' column in ascending order
            ->with('code')  // Ensure 'code' is loaded as a relationship
            ->get();

        // Fetch the last 10 masters for recent data
        $recentMasters = Master::where('mn', $selectedStation)
            ->orderBy('data_time', 'desc')
            ->take(10)
            ->get();

        // Build locations for each station based on the last 6 digits of mn
        $stationLocations = [];
        foreach ($stations as $st) {
            $stationLocations[$st->mn] = $this->resolveLocation($st->mn);
        }

        return view('dashboard', compact('stations', 'latestMaster', 'latestDataList', 'recentMasters', 'stationLocations'));
    }

    private function resolveLocation(string $mn): ?string
    {
        // Use last 6 digits of mn to map to location names
        $suffix = substr($mn, -6);
        $map = [
            '830232' => 'Khafgy2',
            '830241' => 'Khafgy1',
            '830239' => 'Sarar',
            '130353' => 'Al Qaria',
            '830242' => 'Al Naeiria',
            '830235' => 'Aein Dar',
            '830238' => 'Hafr Elbatin3 (MBBR)',
            '830230' => 'Hafr Elbatin2 (MBR)',
            '830233' => 'Hafr Elbatin1 (MBR)',
            '830227' => 'Al Bosira3',
            '830237' => 'Al Bosira1',
            '830240' => 'Al Bosira2',
            '830228' => 'Safwa1',
            '830229' => 'Safwa2',
            '260136' => 'Al Rafia',
            '260137' => 'Sanabis2',
            '830244' => 'Sanabis1',
            '830245' => 'Jarodia1',
            '830236' => 'Jarodia 2',
            '830234' => 'Jarodia 3',
            '830231' => 'Jarodia4',
        ];

        return $map[$suffix] ?? null;
    }

    public function mewa(Request $request)
    {
       
        $selectedStation = 'AQI2407277830243'; 
        // Fetch the latest master record for the specified device (station)
        $latestMaster = Master::where('mn', $selectedStation)->latest('data_time')->first();
    
        if (!$latestMaster) {
            return redirect()->back()->with('device_not_found', true);
        }
    
        // Fetch the latest data for the master, filtered by this specific device (station)
        $latestDataList = DataList::where('master_id', $latestMaster->id)
            ->join('codes', 'data_lists.code_id', '=', 'codes.id')  // Join the codes table
            ->orderBy('codes.order_by', 'asc')  // Sort by the 'order_by' column in ascending order
            ->with('code')  // Ensure 'code' is loaded as a relationship
            ->get();
    
        // Prepare the last 10 readings (masters) grouped by 'name'
        $recentMasters = Master::where('mn', $selectedStation)
            ->latest('data_time')
            ->with(['dataLists.code'])
            ->take(10)
            ->get();
    
        return view('mewa', compact('latestMaster', 'latestDataList', 'recentMasters'));
    }
    

}
