<?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 ReportsController extends Controller
{
    protected $apiBaseUrl;

    public function __construct()
    {
        $this->apiBaseUrl = env('EXTERNAL_API_URL', 'http://localhost:8081/api/');
    }

    private function makeApiRequest($endpoint, $params, $isDownload = false)
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

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

            $baseUrl = rtrim($this->apiBaseUrl, '/');
            $endpoint = ltrim($endpoint, '/');
            $fullUrl = "{$baseUrl}/{$endpoint}";

            Log::info("Making API request to: {$fullUrl}", ['params' => $params]);
            $client = Http::withHeaders([
                'Accept' => $isDownload ? 'text/csv' : 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->timeout(30);

            $response = $client->get($fullUrl, $params);

            Log::info("API response status: {$response->status()}", [
                'endpoint' => $endpoint,
                'headers' => $response->headers()
            ]);

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

            if (!$response->successful()) {
                Log::error("API request failed for {$endpoint}", [
                    'status' => $response->status(),
                    'response' => $response->body(),
                    'headers' => $response->headers()
                ]);
                return null;
            }

            if ($isDownload) {
                return $response;
            }

            return $response->json();
        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            Log::error("Connection error during API request to {$endpoint}", [
                'error' => $e->getMessage(),
                'params' => $params
            ]);
            return null;
        } catch (\Exception $e) {
            Log::error("Unexpected error during API request to {$endpoint}", [
                'error' => $e->getMessage(),
                'params' => $params
            ]);
            return null;
        }
    }

    public function mobileUsage(Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'page_size' => 5,
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            'sorting' => $request->input('sort', 'date|desc'),
            '_search' => $request->input('_search'),
        ];

        $data = $this->makeApiRequest('cms/reportMobileUsage', $params);

        if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
            return $data;
        }

        $mobileUsageData = [];
        $currentPage = $params['page'];
        $lastPage = 1;
        $total = 0;
        $errorMessage = null;

        if ($data && isset($data['data'])) {
            $mobileUsageData = array_map(function ($item) {
                return [
                    'id' => $item['id'] ?? uniqid(),
                    'date' => $item['date'],
                    'activeUsers' => $item['active_users'],
                    'inactiveUsers' => $item['inactive_users'],
                    'lockedUsers' => $item['locked_users'],
                ];
            }, $data['data']);
            $currentPage = $data['meta']['current_page'] ?? 1;
            $lastPage = $data['meta']['last_page'] ?? 1;
            $total = $data['meta']['total'] ?? count($mobileUsageData);
        } elseif ($data && isset($data['message'])) {
            Log::info("API returned message for mobileUsage", ['message' => $data['message']]);
            $errorMessage = $data['message'];
        } else {
            Log::warning("No data returned or invalid response structure for mobileUsage", ['data' => $data]);
            $errorMessage = 'Failed to fetch mobile usage data.';
        }

        return view('pages.reports.mobile-usage-report', compact('mobileUsageData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
    }

    public function exportMobileUsage(Request $request)
    {
        $params = [
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            '_search' => $request->input('_search'),
            'sorting' => $request->input('sort', 'date|desc'),
        ];

        $response = $this->makeApiRequest('cms/reportMobileUsageExport', $params, true);

        if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
            return $response;
        }

        if (!$response) {
            Log::warning("Failed to export mobile usage data", ['params' => $params]);
            return redirect()->back()->with('error', 'Failed to export CSV.');
        }

        $filename = "reports_mobile_usage" . date("mdY") . ".csv";

        return response($response->body(), 200)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', "attachment; filename=\"$filename\"");
    }

    public function registration(Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'page_size' => 5,
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            'sorting' => $request->input('sort', 'date|desc'),
            '_search' => $request->input('_search'),
        ];

        $data = $this->makeApiRequest('cms/reportRegistration', $params);

        if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
            return $data;
        }

        $registrationData = [];
        $currentPage = $params['page'];
        $lastPage = 1;
        $total = 0;
        $errorMessage = null;

        if ($data && isset($data['data'])) {
            $registrationData = array_map(function ($item) {
                return [
                    'id' => $item['id'] ?? uniqid(),
                    'date' => $item['date'],
                    'activatedCards' => $item['activated_cards'],
                    'registeredMembers' => $item['registered_members'],
                ];
            }, $data['data']);
            $currentPage = $data['meta']['current_page'] ?? 1;
            $lastPage = $data['meta']['last_page'] ?? 1;
            $total = $data['meta']['total'] ?? count($registrationData);
        } elseif ($data && isset($data['message'])) {
            Log::info("API returned message for registration", ['message' => $data['message']]);
            $errorMessage = $data['message'];
        } else {
            Log::warning("No data returned or invalid response structure for registration", ['data' => $data]);
            $errorMessage = 'Failed to fetch registration data.';
        }

        return view('pages.reports.registration-report', compact('registrationData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
    }

    public function exportRegistration(Request $request)
    {
        $params = [
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            '_search' => $request->input('_search'),
            'sorting' => $request->input('sort', 'date|desc'),
        ];

        $response = $this->makeApiRequest('cms/reportRegistrationExport', $params, true);

        if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
            return $response;
        }

        if (!$response) {
            Log::warning("Failed to export registration data", ['params' => $params]);
            return redirect()->back()->with('error', 'Failed to export CSV.');
        }

        $filename = "registration" . date("mdY") . ".csv";

        return response($response->body(), 200)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', "attachment; filename=\"$filename\"");
    }

    public function stationRating(Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'page_size' => 5,
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            'sorting' => $request->input('sort', 'date|desc'),
            '_search' => $request->input('_search'),
        ];

        $data = $this->makeApiRequest('cms/reportStationRatings', $params);

        if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
            return $data;
        }

        $stationRatingData = [];
        $currentPage = $params['page'];
        $lastPage = 1;
        $total = 0;
        $errorMessage = null;

        if ($data && isset($data['data'])) {
            $stationRatingData = array_map(function ($item) {
                return [
                    'id' => $item['id'] ?? uniqid(),
                    'transactionDateTime' => $item['date'],
                    'cardNumber' => $item['card_number'],
                    'salesInvoice' => $item['invoice'],
                    'station' => $item['station'],
                    'ratings' => $item['rate'],
                ];
            }, $data['data']);
            $currentPage = $data['meta']['current_page'] ?? 1;
            $lastPage = $data['meta']['last_page'] ?? 1;
            $total = $data['meta']['total'] ?? count($stationRatingData);
        } elseif ($data && isset($data['message'])) {
            Log::info("API returned message for stationRating", ['message' => $data['message']]);
            $errorMessage = $data['message'];
        } else {
            Log::warning("No data returned or invalid response structure for stationRating", ['data' => $data]);
            $errorMessage = 'Failed to fetch station rating data.';
        }

        return view('pages.reports.station-rating-report', compact('stationRatingData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
    }

    public function exportStationRating(Request $request)
    {
        $params = [
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            '_search' => $request->input('_search'),
            'sorting' => $request->input('sort', 'date|desc'),
        ];

        $response = $this->makeApiRequest('cms/reportStationRatingsExport', $params, true);

        if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
            return $response;
        }

        if (!$response) {
            Log::warning("Failed to export station rating data", ['params' => $params]);
            return redirect()->back()->with('error', 'Failed to export CSV.');
        }

        $filename = "reports_station_rating" . date("mdY") . ".csv";

        return response($response->body(), 200)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', "attachment; filename=\"$filename\"");
    }

    public function topUp(Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'page_size' => 5,
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            'sorting' => $request->input('sort', 'transaction_date_time|desc'),
            '_search' => $request->input('_search'),
        ];

        $data = $this->makeApiRequest('cms/reportTopUp', $params);

        if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
            return $data;
        }

        $topUpData = [];
        $currentPage = $params['page'];
        $lastPage = 1;
        $total = 0;
        $errorMessage = null;

        if ($data && isset($data['data'])) {
            $topUpData = array_map(function ($item) {
                return [
                    'id' => $item['id'] ?? uniqid(),
                    'transactionDateTime' => $item['transaction_date_time'],
                    'cardNumber' => $item['card_number'],
                    'topUpAmount' => $item['top_up_amount'],
                ];
            }, $data['data']);
            $currentPage = $data['meta']['current_page'] ?? 1;
            $lastPage = $data['meta']['last_page'] ?? 1;
            $total = $data['meta']['total'] ?? count($topUpData);
        } elseif ($data && isset($data['message'])) {
            Log::info("API returned message for topUp", ['message' => $data['message']]);
            $errorMessage = $data['message'];
        } else {
            Log::warning("No data returned or invalid response structure for topUp", ['data' => $data]);
            $errorMessage = 'Failed to fetch top-up data.';
        }

        return view('pages.reports.top-up-usage-report', compact('topUpData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
    }

    public function exportTopUp(Request $request)
    {
        $params = [
            'date_start' => $request->input('date_start'),
            'date_end' => $request->input('date_end'),
            '_search' => $request->input('_search'),
            'sorting' => $request->input('sort', 'transaction_date_time|desc'),
        ];

        $response = $this->makeApiRequest('cms/reportTopUpExport', $params, true);

        if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
            return $response;
        }

        if (!$response) {
            Log::warning("Failed to export top-up data", ['params' => $params]);
            return redirect()->back()->with('error', 'Failed to export CSV.');
        }

        $filename = "reports_top_up" . date("mdY") . ".csv";

        return response($response->body(), 200)
            ->header('Content-Type', 'text/csv')
            ->header('Content-Disposition', "attachment; filename=\"$filename\"");
    }
}