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

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

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/cardType", [
                '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();

            if ($response->successful() && isset($json['data']) && is_array($json['data'])) {
                $cardTypes = array_map(function ($item) {
                    return [
                        'id' => $item['cardtype_uuid'] ?? null,
                        'cardCode' => $item['code'] ?? '',
                        'cardTypeDescription' => $item['description'] ?? '',
                        'cardTypeShortDescription' => $item['short_description'] ?? '',
                        'cardTypeImage' => $item['image'] ?? '',
                        'virtualCardFontColor' => $item['virtual_card_font_color'] ?? '',
                        'cardTypeCoverImage' => $item['bg_image'] ?? '',
                        'idNumberRequired' => $item['id_number'] ? 'Yes' : 'No',
                        'idNumberDescription' => $item['id_number_description'] ?? '',
                        'termsAndConditions' => $item['terms_and_conditions'] ?? '',
                        'faqs' => $item['faqs'] ?? '',
                        'type' => $item['type'] ?? '',
                    ];
                }, $json['data']);

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

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

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

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

            return view('pages.add-card-types', [
                'fontColors' => ['White', 'Black'],
                'idNumberOptions' => ['Yes', 'No'],
                'cardTypes' => ['Visa', 'MasterCard', 'Amex'],
            ]);
        } catch (\Exception $e) {
            Log::error('Error loading create card type page: ' . $e->getMessage());
            return view('pages.add-card-types', [
                'fontColors' => ['White', 'Black'],
                'idNumberOptions' => ['Yes', 'No'],
                'cardTypes' => ['Visa', 'MasterCard', 'Amex'],
            ]);
        }
    }

    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 card type.');
            }

            $request->validate([
                'code' => 'required|string|max:50',
                'type' => 'required|in:Visa,MasterCard,Amex',
                'description' => 'required|string|max:255',
                'short_description' => 'required|string|max:100',
                'image' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
                'bg_image' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
                'virtual_card_font_color' => 'required|in:White,Black',
                'id_number' => 'required|in:Yes,No',
                'id_number_description' => 'nullable|string|max:255',
                'terms_and_conditions' => 'required|string',
                'faqs' => 'required|string',
            ]);

            $payload = [
                'code' => $request->input('code'),
                'type' => $request->input('type'),
                'description' => $request->input('description'),
                'short_description' => $request->input('short_description'),
                'virtual_card_font_color' => $request->input('virtual_card_font_color'),
                'id_number' => $request->input('id_number') === 'Yes' ? 1 : 0,
                'id_number_description' => $request->input('id_number_description', ''),
                'terms_and_conditions' => $request->input('terms_and_conditions'),
                'faqs' => $request->input('faqs'),
            ];

            $client = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ]);

            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $client = $client->attach('image', file_get_contents($image->getPathname()), $image->getClientOriginalName());
            }

            if ($request->hasFile('bg_image')) {
                $bgImage = $request->file('bg_image');
                $client = $client->attach('bg_image', file_get_contents($bgImage->getPathname()), $bgImage->getClientOriginalName());
            }

            $response = $client->post("{$this->apiBaseUrl}/cardType", $payload);

            $json = $response->json();
            Log::info('API response for creating card type: ', $json);

            if ($response->successful()) {
                Log::info('Card type created successfully: ', $json);
                return redirect()->route('card-types')->with('success', $json['message'] ?? 'Card type added successfully.');
            } else {
                $errorMessage = $json['message'] ?? 'Failed to add card type. Please try again.';
                if (isset($json['errors'])) {
                    $errorMessage .= ' Errors: ' . json_encode($json['errors']);
                }
                throw new \Exception($errorMessage);
            }
        } catch (\Exception $e) {
            Log::error('Error creating card type: ' . $e->getMessage());
            return redirect()->back()->withErrors(['error' => 'An error occurred while adding the card type: ' . $e->getMessage()])->withInput();
        }
    }

    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 type.');
            }

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $cardType = [
                    'id' => $json['data']['cardtype_uuid'] ?? null,
                    'cardCode' => $json['data']['code'] ?? '',
                    'cardTypeDescription' => $json['data']['description'] ?? '',
                    'cardTypeShortDescription' => $json['data']['short_description'] ?? '',
                    'cardTypeImage' => $json['data']['image'] ?? '',
                    'virtualCardFontColor' => $json['data']['virtual_card_font_color'] ?? '',
                    'cardTypeCoverImage' => $json['data']['bg_image'] ?? '',
                    'idNumberRequired' => $json['data']['id_number'] ? 'Yes' : 'No',
                    'idNumberDescription' => $json['data']['id_number_description'] ?? '',
                    'termsAndConditions' => $json['data']['terms_and_conditions'] ?? '',
                    'faqs' => $json['data']['faqs'] ?? '',
                    'type' => $json['data']['type'] ?? '',
                ];
                return view('pages.view-card-types', ['cardType' => $cardType]);
            } else {
                Log::warning('No card type found or invalid API response: ', $json);
                return redirect()->back()->with('error', 'Card type not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching card type for view: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while loading the card type.');
        }
    }

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

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

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $cardType = [
                    'id' => $json['data']['cardtype_uuid'] ?? null,
                    'cardCode' => $json['data']['code'] ?? '',
                    'cardTypeDescription' => $json['data']['description'] ?? '',
                    'cardTypeShortDescription' => $json['data']['short_description'] ?? '',
                    'cardTypeImage' => $json['data']['image'] ?? '',
                    'virtualCardFontColor' => $json['data']['virtual_card_font_color'] ?? '',
                    'cardTypeCoverImage' => $json['data']['bg_image'] ?? '',
                    'idNumberRequired' => $json['data']['id_number'] ? 'Yes' : 'No',
                    'idNumberDescription' => $json['data']['id_number_description'] ?? '',
                    'termsAndConditions' => $json['data']['terms_and_conditions'] ?? '',
                    'faqs' => $json['data']['faqs'] ?? '',
                    'type' => $json['data']['type'] ?? '',
                ];
                return view('pages.edit-card-types', [
                    'cardType' => $cardType,
                    'fontColors' => ['White', 'Black'],
                    'idNumberOptions' => ['Yes', 'No'],
                    'cardTypes' => ['Visa', 'MasterCard', 'Amex'],
                ]);
            } else {
                Log::warning('No card type found or invalid API response: ', $json);
                return redirect()->back()->with('error', 'Card type not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching card type for edit: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while loading the card type.');
        }
    }

    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 card type.');
            }

            $request->validate([
                'code' => 'required|string|max:50',
                'type' => 'required|in:Visa,MasterCard,Amex',
                'description' => 'required|string|max:255',
                'short_description' => 'required|string|max:100',
                'image' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
                'bg_image' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
                'virtual_card_font_color' => 'required|in:White,Black',
                'id_number' => 'required|in:Yes,No',
                'id_number_description' => 'nullable|string|max:255',
                'terms_and_conditions' => 'required|string',
                'faqs' => 'required|string',
            ]);

            $payload = [
                'code' => $request->input('code'),
                'type' => $request->input('type'),
                'description' => $request->input('description'),
                'short_description' => $request->input('short_description'),
                'virtual_card_font_color' => $request->input('virtual_card_font_color'),
                'id_number' => $request->input('id_number') === 'Yes' ? 1 : 0,
                'id_number_description' => $request->input('id_number_description', ''),
                'terms_and_conditions' => $request->input('terms_and_conditions'),
                'faqs' => $request->input('faqs'),
            ];

            $client = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ]);

            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $client = $client->attach('image', file_get_contents($image->getPathname()), $image->getClientOriginalName());
            }

            if ($request->hasFile('bg_image')) {
                $bgImage = $request->file('bg_image');
                $client = $client->attach('bg_image', file_get_contents($bgImage->getPathname()), $bgImage->getClientOriginalName());
            }

            $response = $client->post("{$this->apiBaseUrl}/cardTypeUpdate/{$uuid}", $payload);

            $json = $response->json();
            Log::info('API response for updating card type: ', $json);

            if ($response->successful()) {
                Log::info('Card type updated successfully: ', $json);
                return redirect()->route('card-types')->with('success', $json['message'] ?? 'Card type updated successfully.');
            } else {
                $errorMessage = $json['message'] ?? 'Failed to update card type. Please try again.';
                if (isset($json['errors'])) {
                    $errorMessage .= ' Errors: ' . json_encode($json['errors']);
                }
                return redirect()->back()->withErrors(['error' => $errorMessage]);
            }
        } catch (\Exception $e) {
            Log::error('Error updating card type: ' . $e->getMessage());
            return redirect()->back()->withErrors(['error' => 'An error occurred while updating the card type: ' . $e->getMessage()]);
        }
    }

    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 card type.');
            }

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

            if ($response->successful()) {
                Log::info('Card type deleted successfully: ' . $uuid);
                return redirect()->route('card-types')->with('success', 'Card type deleted successfully.');
            } else {
                Log::warning('Failed to delete card type: ', $response->json());
                return redirect()->back()->with('error', $response->json()['message'] ?? 'Failed to delete card type. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error deleting card type: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting the card type.');
        }
    }

    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 card types.');
            }

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

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

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

            if ($response->successful()) {
                Log::info('Card types batch deleted successfully: ', $uuids);
                return redirect()->route('card-types')->with('success', 'Selected card types deleted successfully.');
            } else {
                Log::warning('Failed to batch delete card types: ', $response->json());
                return redirect()->back()->with('error', $response->json()['message'] ?? 'Failed to delete card types. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Error batch deleting card types: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while deleting the card types.');
        }
    }
}