<?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 CardMemberController 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 card-member');
                return redirect()->route('login')->with('error', 'Please log in to view card members.');
            }

            $page = $request->input('page', 1);
            $pageSize = 5; // Fixed at 5 per page as per sample
            $search = $request->input('_search', null);

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

            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("Card Member API Response (Page {$page}): ", $json);

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $members = array_map(function ($member) {
                    Log::info('Processing card member record: ', $member);
                    return [
                        'id' => $member['lcard_uuid'] ?? null,
                        'cardNumber' => $member['card_number'] ?? '',
                        'firstName' => $member['firstname'] ?? '',
                        'lastName' => $member['lastname'] ?? '',
                        'birthday' => $member['birthdate'] ?? '',
                        'cardType' => $member['card_type'] ?? '',
                        'status' => $member['is_validated'] ? 'Active' : 'Inactive',
                    ];
                }, $json['data']);

                $total = $json['meta']['total'] ?? count($members);
                $lastPage = $json['meta']['last_page'] ?? ceil($total / $pageSize);
            } else {
                Log::warning('No card member data found or invalid API response: ', $json);
                $members = [];
                $total = 0;
                $lastPage = 1;
            }

            return view('pages.member management.card-member', [
                'members' => $members,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'total' => $total,
                'search' => $search,
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching card member data: ' . $e->getMessage());
            return view('pages.member management.card-member', [
                'members' => [],
                'currentPage' => 1,
                'lastPage' => 1,
                'total' => 0,
                'search' => $search,
            ]);
        }
    }

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

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

            $page = $request->input('page', 1);
            $pageSize = 5; // Fixed at 5 per page as per sample
            $search = $request->input('_search', null);

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cms/member", [
                'page' => $page,
                'page_size' => $pageSize,
                '_search' => $search,
                '_locked' => 1, // Fetch only locked accounts
            ]);

            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("Locked Account API Response (Page {$page}): ", $json);

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $members = array_map(function ($member) {
                    Log::info('Processing locked account record: ', $member);
                    return [
                        'id' => $member['lcard_uuid'] ?? null,
                        'cardNumber' => $member['card_number'] ?? '',
                        'firstName' => $member['firstname'] ?? '',
                        'lastName' => $member['lastname'] ?? '',
                        'birthday' => $member['birthdate'] ?? '',
                        'cardType' => $member['card_type'] ?? '',
                        'status' => $member['is_validated'] ? 'Active' : 'Inactive',
                    ];
                }, $json['data']);

                $total = $json['meta']['total'] ?? count($members);
                $lastPage = $json['meta']['last_page'] ?? ceil($total / $pageSize);
            } else {
                Log::warning('No locked account data found or invalid API response: ', $json);
                $members = [];
                $total = 0;
                $lastPage = 1;
            }

            return view('pages.member management.locked-account', [
                'members' => $members,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'total' => $total,
                'search' => $search,
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching locked account data: ' . $e->getMessage());
            return view('pages.member management.locked-account', [
                'members' => [],
                'currentPage' => 1,
                'lastPage' => 1,
                'total' => 0,
                'search' => $search,
            ]);
        }
    }

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

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

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $member = [
                    'id' => $json['data']['lcard_uuid'] ?? null,
                    'cardNumber' => $json['data']['card_number'] ?? '',
                    'firstName' => $json['data']['firstname'] ?? '',
                    'lastName' => $json['data']['lastname'] ?? '',
                    'birthday' => $json['data']['birthdate'] ?? '',
                    'cardType' => $json['data']['card_type'] ?? '',
                    'status' => $json['data']['is_validated'] ? 'Active' : 'Inactive',
                ];

                // Determine the view based on the referring route
                $previousUrl = url()->previous();
                if (str_contains($previousUrl, 'locked-account')) {
                    return view('pages.locked-account-view', ['member' => $member]);
                }
                return view('pages.card-member-view', ['member' => $member]);
            } else {
                Log::warning('No card member found or invalid API response: ', $json);
                return redirect()->back()->with('error', 'Card member not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching card member for view: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while loading the card member.');
        }
    }

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

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

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

            if ($response->successful()) {
                return redirect()->route('locked-account')->with('success', 'Account activated successfully.');
            } else {
                Log::warning('Failed to activate account: ', $response->json());
                return redirect()->back()->with('error', $response->json()['message'] ?? 'Failed to activate account. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error activating account: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while activating the account.');
        }
    }
}