<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class StationController extends Controller
{
    protected $apiBaseUrl = 'http://192.168.100.6:8081/api/cms';

    public function index(Request $request)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

            if (!$accessToken) {
                Log::info('No access token found, redirecting to login from stations');
                return redirect()->route('login')->with('error', 'Please log in to view stations.');
            }

            $page = $request->input('page', 1);
            $pageSize = 5;
            $search = $request->input('_search', null);
            $sort = $request->input('sort', 'station_code|asc');

            Log::info('Initiating API request to fetch stations', [
                'url' => "{$this->apiBaseUrl}/getStations",
                'params' => [
                    'page' => $page,
                    'page_size' => $pageSize,
                    '_search' => $search,
                    'sort' => $sort,
                ],
            ]);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->timeout(30)->get("{$this->apiBaseUrl}/getStations", [
                'page' => $page,
                'page_size' => $pageSize,
                '_search' => $search,
                'sort' => $sort,
            ]);

            $json = $response->json();
            $rawResponse = $response->body();

            Log::info('API response received for stations', [
                'status' => $response->status(),
                'headers' => $response->headers(),
                'data' => $json,
                'raw_response' => $rawResponse,
                'reason' => $response->reason(),
            ]);

            if ($response->status() === 401 || $response->status() === 403) {
                Log::warning('Unauthorized or Forbidden API response for stations', ['response' => $json]);
                return redirect()->route('login')->with('error', 'Your session has expired. Please log in again.');
            }

            if ($response->successful() && isset($json['code']) && $json['code'] == 200 && isset($json['data']) && is_array($json['data'])) {
                $stations = array_map(function ($station) {
                    return [
                        'id' => $station['station_uuid'] ?? '',
                        'station_code' => $station['code'] ?? '',
                        'station_name' => $station['description'] ?? '',
                        'branch_name' => $station['branch_name'] ?? '',
                        'date_created' => $station['date_created'] ?? '',
                        'created_by' => $station['created_by'] ?? '',
                        'modified_by' => $station['modified_by'] ?? '',
                        'date_modified' => $station['date_modified'] ?? '',
                    ];
                }, $json['data']);

                // Use meta for pagination if provided, else calculate locally
                $total = $json['meta']['total'] ?? count($stations);
                $lastPage = $json['meta']['last_page'] ?? ceil($total / $pageSize);

                // Apply search filter locally if needed
                if ($search) {
                    $searchTerm = strtolower($search);
                    $stations = array_filter($stations, function ($station) use ($searchTerm) {
                        return str_contains(strtolower($station['station_code'] ?? ''), $searchTerm) ||
                               str_contains(strtolower($station['station_name'] ?? ''), $searchTerm);
                    });
                    $stations = array_values($stations);
                    $total = count($stations);
                    $lastPage = ceil($total / $pageSize);
                }

                // Apply sorting locally
                if ($sort) {
                    [$sortField, $sortDir] = explode('|', $sort);
                    usort($stations, function ($a, $b) use ($sortField, $sortDir) {
                        $aValue = $a[$sortField] ?? '';
                        $bValue = $b[$sortField] ?? '';
                        return $sortDir === 'asc' ? strcmp($aValue, $bValue) : strcmp($bValue, $aValue);
                    });
                }

                // Paginate locally
                $start = ($page - 1) * $pageSize;
                $stations = array_slice($stations, $start, $pageSize);
            } else {
                Log::warning('No station data found or invalid API response', ['response' => $json]);
                $stations = [];
                $total = 0;
                $lastPage = 1;
            }

            Log::info('Processed stations data', [
                'stations_count' => count($stations),
                'total' => $total,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'stations' => $stations,
            ]);

            return view('pages.station locator.stations', [
                'stations' => $stations,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'total' => $total,
                'search' => $search,
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching stations: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
            ]);
            return view('pages.station locator.stations', [
                'stations' => [],
                'currentPage' => 1,
                'lastPage' => 1,
                'total' => 0,
                'search' => $search,
            ])->with('error', 'Failed to fetch stations: ' . $e->getMessage());
        }
    }
}