<?php

namespace App\Http\Controllers\Admin\Api;

use Agence104\LiveKit\VideoGrant;
use App\Classes\Constant;
use App\Events\AppointmentBooked;
use App\Events\PaymentProcessed;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Item;
use App\Models\ItemHistory;
use App\Models\Lab;
use App\Models\LabKit;
use App\Models\LabkitOrderItem;
use App\Models\LicenseNumberModel;
use App\Models\MedicalHistoryAnswer;
use App\Models\Patient;
use App\Models\PatientNote;
use App\Models\PatientPlan;
use App\Models\PatientPrescription;
use App\Models\PatientRegActivity;
use App\Models\Plan;
use App\Models\PlanV1;
use App\Models\Prescription;
use App\Models\ProfileAnswer;
use App\Models\ProfileCategory;
use App\Models\QuestionBuilder;
use App\Models\Setting;
use App\Models\Subscription;
use App\Models\Telemedpro;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use DateTime;
use DateTimeZone;
use Error;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Agence104\LiveKit\AccessToken;
use Agence104\LiveKit\AccessTokenOptions;
use Agence104\LiveKit\RoomCreateOptions;
use Agence104\LiveKit\RoomServiceClient;
use Illuminate\Auth\Access\AuthorizationException;

class SubscriptionController extends Controller
{
    protected $url;
    protected $user;
    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
        $this->user = Auth::guard('admin')->user();
    }

    public function getSubscriptionList()
    {
        try {
            $this->authorizeForUser($this->user, 'list', new Subscription);

            $subscriptions = Subscription::with(['cart', 'item.plansV1', 'patient'])
                ->join('patients', 'subscription.patient_id', '=', 'patients.id')  // Join with the patient table
                ->join('items', 'subscription.item_id', '=', 'items.id')  // Join with the plansV1 table
                ->join('plans_v1', 'items.plans_id', '=', 'plans_v1.id')  // Join with the plansV1 table

                ->select([
                    'subscription.*',
                    'patients.first_name',
                    'patients.last_name',
                    'plans_v1.title as product_title',
                    'plans_v1.price as price'
                ]);  // Select necessary columns

            return DataTables::of($subscriptions)
                ->addColumn('product_title', function ($subscription) {
                    return $subscription->item?->plansV1?->title ?? 'N/A';
                })
                ->addColumn('price', function ($subscription) {
                    return $subscription->item?->plansV1?->price ?? 'N/A';
                })
                ->addColumn('currency', function ($subscription) {
                    $plan = $subscription->item?->plansV1;
                    return $plan ? $plan->currency : 'N/A';
                })
                ->addColumn('first_name', function ($subscription) {
                    return $subscription->first_name ?? 'N/A';
                })
                ->addColumn('last_name', function ($subscription) {
                    return $subscription->last_name ?? 'N/A';
                })
                ->filterColumn('first_name', function ($query, $keyword) {
                    $query->where('patients.first_name', 'like', "%{$keyword}%");
                })
                ->filterColumn('last_name', function ($query, $keyword) {
                    $query->where('patients.last_name', 'like', "%{$keyword}%");
                })
                ->filterColumn('product_title', function ($query, $keyword) {
                    $query->where('plans_v1.title', 'like', "%{$keyword}%");
                })
                ->filterColumn('product_price', function ($query, $keyword) {
                    $query->where('plans_v1.price', 'like', "%{$keyword}%");
                })
                ->make(true);
        } catch (AuthorizationException $e) {
            return $e->getMessage();
        }
    }



    public function updateSubscription(Request $request, $subid)
    {
        try {
            $this->authorizeForUser($this->user, 'edit', new Subscription);
            // Find the subscription
            $subscription = Subscription::find($subid);
            if (!$subscription) {
                return response()->json(['message' => 'Subscription not found'], 404);
            }
            // Define the fillable fields
            $fillable = [
                'subscription_start_date',
                'subscription_renewal_date',
                'subscription_status',
                'cart_id',
                'item_id',
                'patient_id',
                'status'
            ];
            // Filter the request data to only include fillable fields that are present
            $dataToUpdate = array_filter(
                $request->only($fillable),
                function ($value) {
                    return $value !== null;
                }
            );

            // Validate the filtered data
            $validator = Validator::make($dataToUpdate, [
                'subscription_start_date' => 'required',
                'subscription_renewal_date' => 'required',
                'subscription_status' => 'string',
                'cart_id' => 'exists:carts,id',
                'item_id' => 'exists:items,id',
                'patient_id' => 'exists:patients,id',
                'status' => 'string',
            ]);

            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 422);
            }
            // Update the subscription
            $subscription->update($dataToUpdate);

            return response()->json(['message' => 'Subscription updated successfully', 'data' => $subscription], 200);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function CreateSubscription(Request $request)
    {
        try {
            $this->authorizeForUser($this->user, 'add', new Subscription);
            // Validate the incoming request data
            $validator = Validator::make($request->all(), [
                'subscription_start_date' => 'required',
                'subscription_renewal_date' => 'required',
                'subscription_status' => 'required',
                'cart_id' => 'required|exists:carts,id',
                'item_id' => 'required|exists:items,id',
                'patient_id' => 'required|exists:patients,id',
                //'status' => 'required'
            ]);

            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 422);
            }

            // Create the subscription
            $subscription = Subscription::create($request->all());

            return response()->json([
                'message' => 'Subscription created successfully',
                'data' => $subscription
            ], 201);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }

    public function getSubscription(Subscription $subscription, Request $request)
    {
        try {
            $this->authorizeForUser($this->user, 'list', new Subscription);
            return response()->json([
                'data' => $subscription
            ], 201);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function deleteSubscription(Subscription $subscription, Request $request)
    {
        try {
            $this->authorizeForUser($this->user, 'delete', new Subscription);
            $subscription->delete();
            return response()->json([
                'status' => 'deleted',
                'message' => 'subscription deleted'
            ], 201);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
}
