<?php

namespace App\Http\Controllers\Api\V1\User;

use Exception;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Http\Helpers\Response;
use App\Http\Controllers\Controller;
use App\Constants\PaymentGatewayConst;
use Illuminate\Support\Facades\Validator;
use App\Providers\Admin\BasicSettingsProvider;
use App\Http\Helpers\Api\Helpers as ApiResponse;
use App\Models\ParlourBooking;
use PDF;

class TransactionController extends Controller
{
    public function slugValue($slug)
    {
        $values =  [
            'payment-methods'   => PaymentGatewayConst::PAYMENTMETHOD,
        ];

        if (!array_key_exists($slug, $values)) return abort(404);
        return $values[$slug];
    }

    public function log(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'slug'      => "nullable|string|in:payment-methods",
        ]);
        if ($validator->fails()) return Response::error($validator->errors()->all(), []);

        $validated = $validator->validate();

        try {

            if (isset($validated['slug']) && $validated['slug'] != "") {
                $transactions = Transaction::auth()->where("type", $this->slugValue($validated['slug']))->orderByDesc("id")->get();
            } else {
                $transactions = Transaction::auth()->orderByDesc("id")->get();
            }

            $transactions->makeHidden([
                'id',
                'user_type',
                'user_id',
                'wallet_id',
                'payment_gateway_currency_id',
                'request_amount',
                'exchange_rate',
                'percent_charge',
                'fixed_charge',
                'total_charge',
                'total_payable',
                'receiver_type',
                'receiver_id',
                'available_balance',
                'payment_currency',
                'input_values',
                'details',
                'reject_reason',
                'remark',
                'stringStatus',
                'updated_at',
                'gateway_currency',
            ]);
        } catch (Exception $e) {
            return Response::error([__('Something went wrong! Please try again')], [], 500);
        }

        return Response::success([__('Transactions fetch successfully!')], [
            'instructions'  => [
                'slug'      => "payment-methods",
                'status'    => "1: Success, 2: Pending"
            ],
            'transaction_types' => [
                PaymentGatewayConst::PAYMENTMETHOD,

            ],
            'transactions'  => $transactions,
        ], 200);
    }

    public function bookingHistory(BasicSettingsProvider $basic_settings)
    {



        try {
            $user_id = auth()->user()->id;
            $image_paths = [
                'base_url'          => url("/"),
                'path_location'     => files_asset_path_basename("site-section"),
                'default_image'     => files_asset_path_basename("default"),
            ];
            // Retrieve booking data
            $booking_data = ParlourBooking::where('user_id', $user_id)
                ->with(['parlour', 'schedule', 'payment_gateway', 'user'])
                ->orderByDesc('id')
                ->get();

            $data = [
                'image_path' => $image_paths,
                'data'  => $booking_data,
                'cur_code' => get_default_currency_code(),
            ];

            $message = ['success' => [__('Request data fetch successfully!')]];
            return ApiResponse::success($message, $data);
        } catch (Exception $e) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }
    }

    public function details($slug)
    {

        $validator = Validator::make(
            ['slug' => $slug],
            ['slug' => 'required|string|exists:parlour_bookings,slug']
        );

        if ($validator->fails()) {
            $error = ['error' => [$validator->errors()->all()]];
            return ApiResponse::onlyValidation($error);
        }

        try {
            $user_id = auth()->user()->id;

            // Retrieve booking details
            $details = ParlourBooking::where('user_id', $user_id)
                ->with(['parlour', 'schedule', 'payment_gateway'])
                ->where('slug', $slug)
                ->first();
            $data = [
                'data'  => $details,
                'cur_code' =>  get_default_currency_code(),
            ];

            if ($data) {
                $message = ['success' => [__('User Booking History')]];
                return ApiResponse::success($message, $data);
            } else {
                $message = ['error' => [__('Something went wrong! Please try again')]];
                return ApiResponse::onlyError($message);
            }
        } catch (\Exception $e) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }
    }

    /**
     * Download booking details as PDF (API)
     */
    public function downloadPdf(Request $request, $slug)
    {

        $user = auth()->user();
        if (!$user) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }

        $data = ParlourBooking::where('user_id', $user->id)
            ->with(['parlour', 'schedule', 'payment_gateway'])
            ->where('slug', $slug)
            ->first();

        if (!$data) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }

        return Response::success([__('PDF Download Link Fetch Successfully!')], [
            'download_link' => route('global.download.pdf', $data->slug)
        ], 200);
    }

    /**
     * Download booking details as PDF (API)
     */
    public function review(Request $request)
    {

        $user = auth()->user();
        if (!$user) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }

        $booking_id = $request->booking_id;
        if (!$booking_id) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }

        $data = ParlourBooking::where('user_id', $user->id)
            ->with(['parlour', 'schedule', 'payment_gateway'])
            ->where('id', $booking_id)
            ->first();


        if (!$data) {
            $message = ['error' => [__('Booking not found')]];
            return ApiResponse::onlyError($message);
        }

        if ($request->review < 1 || $request->review > 5) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }

        try {

            $data->update([
                'review' => $request->review,
                'comment' => $request->comment
            ]);
        } catch (\Exception $e) {
        }

        $message = ['success' => [__('Rating Submitted')]];
        return ApiResponse::success($message, $data);
    }

    /**
     * Download booking details as PDF
     */
    public function responsePdf($slug)
    {
        $user_id = auth()->user()->id;
        $data = ParlourBooking::where('user_id', $user_id)
            ->with(['parlour', 'schedule', 'payment_gateway'])
            ->where('slug', $slug)
            ->firstOrFail();

        $page_title = "Booking Details";

        // Load the view with data
        $pdf = PDF::loadView('user.sections.my-booking.pdf-details', compact('page_title', 'data'));

        // Download the PDF with a filename
        return $pdf->download('booking-details-' . $data->trx_id . '.pdf');
    }
}
