<?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 TopUpController extends Controller
{
    protected $apiBaseUrl = 'http://192.168.100.6:8081/api';

   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 top-up');
            return redirect()->route('login')->with('error', 'Please log in to view top-ups.');
        }

        // Get the requested page from the request (default to 1)
        $page = $request->input('page', 1);
        $perPage = 5; // Set to 5 items per page

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->get("{$this->apiBaseUrl}/cms/topUp", [
            'page' => $page,
            'per_page' => $perPage,
        ]);

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

        $json = $response->json();

        Log::info("TopUp API Response (Page {$page}): ", $json);

        if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
            $topups = array_map(function ($topup) {
                Log::info('Processing top-up record: ', $topup);
                return [
                    'topup_uuid' => $topup['topup_uuid'] ?? $topup['id'] ?? null,
                    'freeCode' => $topup['fee_code'] ?? 'N/A',
                    'name' => $topup['name'] ?? 'Unnamed',
                    'value' => $topup['amount'] ?? 0,
                    'type' => $topup['type'] ?? 'Unknown',
                ];
            }, $json['data']);

            // Pass pagination metadata to the view
            $total = $json['meta']['total'] ?? count($topups); // Total items, adjust based on API response
            $lastPage = $json['meta']['last_page'] ?? ceil($total / $perPage); // Calculate last page

            return view('pages.top-up', [
                'topups' => $topups,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'total' => $total,
            ]);
        } else {
            Log::warning('No top-up data found or invalid API response: ', $json);
            return view('pages.top-up', [
                'topups' => [],
                'currentPage' => 1,
                'lastPage' => 1,
                'total' => 0,
            ]);
        }
    } catch (\Exception $e) {
        Log::error('Error fetching top-up data: ' . $e->getMessage());
        return view('pages.top-up', [
            'topups' => [],
            'currentPage' => 1,
            'lastPage' => 1,
            'total' => 0,
        ]);
    }
}
    public function create()
    {
        try {
            $user = Session::get('user');
            $accessToken = $user['access_token'] ?? null;

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

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/generateFeeCode");

            $json = $response->json();

            if ($response->successful() && isset($json['data']['fee_code'])) {
                $freeCode = $json['data']['fee_code'];
                return view('pages.add-top-up', ['freeCode' => $freeCode]);
            } else {
                Log::warning('Failed to generate fee code: ', $json);
                return view('pages.add-top-up', ['freeCode' => '']);
            }
        } catch (\Exception $e) {
            Log::error('Error generating fee code: ' . $e->getMessage());
            return view('pages.add-top-up', ['freeCode' => '']);
        }
    }

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

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to add a top-up.');
            }

            $validated = $request->validate([
                'freeCode' => 'required|string|max:255',
                'name' => 'required|string|max:255',
                'value' => 'required|numeric|min:0',
                'type' => 'required|in:1,2,3',
            ]);

            $payload = [
                'fee_code' => $validated['freeCode'],
                'name' => $validated['name'],
                'amount' => $validated['value'],
                'type' => $validated['type'],
            ];

            Log::info('API Payload for creating top-up: ', $payload);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->post("{$this->apiBaseUrl}/cms/topUp", $payload);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Top-up created successfully: ', $json);
                return redirect()->route('top-up')
                    ->with('success', $json['message'] ?? 'Top-up added successfully');
            } else {
                Log::error('Failed to create top-up: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to add top-up.');
            }
        } catch (\Exception $e) {
            Log::error('Error creating top-up: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while adding the top-up.');
        }
    }

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

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

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/topUp/{$uuid}");

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $topup = [
                    'topup_uuid' => $json['data']['topup_uuid'],
                    'freeCode' => $json['data']['fee_code'],
                    'name' => $json['data']['name'],
                    'value' => $json['data']['amount'],
                    'type' => $json['data']['type'],
                ];
                return view('pages.view-top-up', ['topup' => $topup]);
            } else {
                Log::warning('Top-up not found: ', $json);
                return redirect()->route('top-up')->with('error', $json['message'] ?? 'Top-up not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching top-up: ' . $e->getMessage());
            return redirect()->route('top-up')->with('error', 'An error occurred while fetching the top-up.');
        }
    }

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

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

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/topUp/{$uuid}");

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $topup = [
                    'topup_uuid' => $json['data']['topup_uuid'],
                    'freeCode' => $json['data']['fee_code'],
                    'name' => $json['data']['name'],
                    'value' => $json['data']['amount'],
                    'type' => $json['data']['type'],
                ];
                return view('pages.edit-top-up', ['topup' => $topup]);
            } else {
                Log::warning('Top-up not found: ', $json);
                return redirect()->route('top-up')->with('error', $json['message'] ?? 'Top-up not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching top-up for edit: ' . $e->getMessage());
            return redirect()->route('top-up')->with('error', 'An error occurred while fetching the top-up.');
        }
    }

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

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to update a top-up.');
            }

            $validated = $request->validate([
                'freeCode' => 'required|string|max:255',
                'name' => 'required|string|max:255',
                'value' => 'required|numeric|min:0',
                'type' => 'required|in:Prepaid,Postpaid,Bonus',
            ]);

            $payload = [
                'fee_code' => $validated['freeCode'],
                'name' => $validated['name'],
                'amount' => $validated['value'],
                'type' => $validated['type'],
            ];

            Log::info('API Payload for updating top-up: ', $payload);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->put("{$this->apiBaseUrl}/cms/topUp/{$uuid}", $payload);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Top-up updated successfully: ', $json);
                return redirect()->route('top-up')
                    ->with('success', $json['message'] ?? 'Top-up updated successfully');
            } else {
                Log::error('Failed to update top-up: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to update top-up.');
            }
        } catch (\Exception $e) {
            Log::error('Error updating top-up: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while updating the top-up.');
        }
    }

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

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to delete a top-up.');
            }

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->delete("{$this->apiBaseUrl}/cms/topUp/{$uuid}");

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Top-up deleted successfully: ', $json);
                return redirect()->route('top-up')
                    ->with('success', $json['message'] ?? 'Top-up deleted successfully');
            } else {
                Log::error('Failed to delete top-up: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to delete top-up.');
            }
        } catch (\Exception $e) {
            Log::error('Error deleting top-up: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting the top-up.');
        }
    }

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

            if (!$accessToken) {
                return redirect()->route('login')->with('error', 'Please log in to delete top-ups.');
            }

            $uuids = $request->input('topup_uuid', []);

            if (empty($uuids)) {
                return redirect()->back()->with('error', 'No top-ups selected for deletion.');
            }

            Log::info('Batch delete UUIDs: ', $uuids);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->delete("{$this->apiBaseUrl}/cms/topUpBatchDelete", [
                'topup_uuid' => $uuids,
            ]);

            $json = $response->json();

            if ($response->successful()) {
                Log::info('Batch delete successful for UUIDs: ', $uuids);
                return redirect()->route('top-up')
                    ->with('success', $json['message'] ?? 'Top-ups deleted successfully');
            } else {
                Log::error('Failed to batch delete top-ups: ', $json);
                return redirect()->back()->with('error', $json['message'] ?? 'Failed to delete top-ups.');
            }
        } catch (\Exception $e) {
            Log::error('Error in batch delete: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting top-ups.');
        }
    }
}