<?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 TermsAndPrivacyController 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 terms-and-privacy');
                return redirect()->route('login')->with('error', 'Please log in to view terms and privacy.');
            }

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

            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $accessToken,
            ])->get("{$this->apiBaseUrl}/TermsAndPrivacy", [
                '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'])) {
                $termsAndPrivacy = array_map(function ($item) {
                    return [
                        'id' => $item['tp_uuid'] ?? null,
                        'title' => $item['title'] ?? '',
                        'details' => $item['details'] ?? '',
                        'type' => $item['type'] == 1 ? 'Terms' : ($item['type'] == 2 ? 'Privacy' : 'Unknown'),
                    ];
                }, $json['data']);

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

            return view('pages.about us.terms-and-privacy', [
                'termsAndPrivacy' => $termsAndPrivacy,
                'currentPage' => $page,
                'lastPage' => $lastPage,
                'total' => $total,
                'search' => $search,
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching terms and privacy: ' . $e->getMessage());
            return view('pages.about us.terms-and-privacy', [
                'termsAndPrivacy' => [],
                '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 terms or privacy.');
            }

            return view('pages.terms-and-privacy.create', ['types' => ['1' => 'Terms', '2' => 'Privacy']]);
        } catch (\Exception $e) {
            Log::error('Error loading create terms and privacy page: ' . $e->getMessage());
            return view('pages.terms-and-privacy.create', ['types' => ['1' => 'Terms', '2' => 'Privacy']]);
        }
    }

    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 terms or privacy.');
            }

            $request->validate([
                'title' => 'required|string|max:255',
                'details' => 'required|string',
                'type' => 'required|in:1,2',
            ]);

            $payload = [
                'title' => $request->input('title'),
                'details' => $request->input('details'),
                'type' => (int) $request->input('type'),
            ];

            Log::info('Data being sent to API for creating terms or privacy: ', $payload);

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

            $json = $response->json();
            Log::info('API response for creating terms or privacy: ', $json);

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

    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 terms or privacy.');
            }

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $item = [
                    'id' => $json['data']['tp_uuid'] ?? null,
                    'title' => $json['data']['title'] ?? '',
                    'details' => $json['data']['details'] ?? '',
                    'type' => $json['data']['type'] == 1 ? 'Terms' : ($json['data']['type'] == 2 ? 'Privacy' : 'Unknown'),
                ];
                return view('pages.terms-and-privacy.show', ['item' => $item]);
            } else {
                Log::warning('No terms or privacy found or invalid API response: ', $json);
                return redirect()->back()->with('error', 'Terms or privacy not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching terms or privacy for view: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while loading the terms or privacy.');
        }
    }

    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 terms or privacy.');
            }

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

            $json = $response->json();

            if ($response->successful() && isset($json['data'])) {
                $item = [
                    'id' => $json['data']['tp_uuid'] ?? null,
                    'title' => $json['data']['title'] ?? '',
                    'details' => $json['data']['details'] ?? '',
                    'type' => $json['data']['type'] ?? '',
                ];
                return view('pages.terms-and-privacy.edit', ['item' => $item, 'types' => ['1' => 'Terms', '2' => 'Privacy']]);
            } else {
                Log::warning('No terms or privacy found or invalid API response: ', $json);
                return redirect()->back()->with('error', 'Terms or privacy not found.');
            }
        } catch (\Exception $e) {
            Log::error('Error fetching terms or privacy for edit: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while loading the terms or privacy.');
        }
    }

    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 terms or privacy.');
            }

            $request->validate([
                'title' => 'required|string|max:255',
                'details' => 'required|string',
                'type' => 'required|in:1,2',
            ]);

            $payload = [
                'title' => $request->input('title'),
                'details' => $request->input('details'),
                'type' => (int) $request->input('type'),
            ];

            Log::info('Data being sent to API for updating terms or privacy: ', $payload);

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

            $json = $response->json();
            Log::info('API response for updating terms or privacy: ', $json);

            if ($response->successful()) {
                Log::info('Terms or privacy updated successfully: ', $json);
                return redirect()->route('terms-and-privacy')->with('success', $json['message'] ?? 'Terms or privacy updated successfully.');
            } else {
                $errorMessage = $json['message'] ?? 'Failed to update terms or privacy. Please try again.';
                if (isset($json['errors'])) {
                    $errorMessage .= ' Errors: ' . json_encode($json['errors']);
                }
                return redirect()->back()->with('error', $errorMessage);
            }
        } catch (\Exception $e) {
            Log::error('Error updating terms or privacy: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while updating the terms or privacy: ' . $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 terms or privacy.');
            }

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

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

    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 terms or privacy.');
            }

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

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

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

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