<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\LabKit;
use App\Models\Telemedpro;
use App\Models\Patient;
use App\Models\PatientNote;
use App\Models\PatientPlan;
use App\Models\PatientPrescription;
use App\Models\PatientRegActivity;
use App\Models\PlanV1;
use App\Models\Prescription;
use App\Models\ProfileCategory;
use App\Models\QuestionBuilder;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DateTime;
use Faker\Factory as Faker;

class InsertDataForApp extends Command
{
    protected $signature = 'insert:data';

    protected $description = 'Insert plans data into the database based on the provided type';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        /* for ($i = 0; $i < 10; $i++) {
            Telemedpro::create([
                'name' => 'Telemedpro ' . ($i + 1),
                'email' => 'telemedpro' . ($i + 1) . '@example.com',
                'phone' => '123-456-789' . $i,
            ]);
        } */

        $faker = Faker::create();

        for ($i = 500; $i < 800; $i++) {
            $patient = Patient::create([
                'first_name' => $faker->firstName,
                'last_name' => $faker->lastName,
                'email' => $faker->unique()->safeEmail,
                'phone' => $faker->phoneNumber,
                'password' => bcrypt("12345"),
                'address' => $faker->address,
                'city' => $faker->city,
                'state' => $faker->state,
                'zip_code' => $faker->postcode,
                'lat' => $faker->latitude,
                'long' => $faker->longitude,
                'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
                'recording_switch' => $faker->boolean,
                'country' => $faker->country,
                'phone_no' => $faker->phoneNumber,
                'shipping_address' => $faker->address,
                'shipping_city' => $faker->city,
                'shipping_state' => $faker->state,
                'shipping_country' => $faker->country,
                'shipping_zipcode' => $faker->postcode,
                'timezone' => 'UTC',
                'gender' => $faker->randomElement(['male', 'female']),
                'marital_status' => $faker->randomElement(['single', 'married']),
                'height' => $faker->numberBetween(150, 200), // Height in cm
                'weight' => $faker->numberBetween(50, 100) // Weight in kg
            ]);

            PatientRegActivity::create([
                'patient_id' => $patient->id,
                'activity' => 'patient_registered'
            ]);
            $plans = PlanV1::all();
            PatientPlan::create([
                'patient_id' => $patient->id,
                'plan_id' => $plans->random()->id,
            ]);
            /* } */

            $telemedpros = Telemedpro::all();
            #$patients = Patient::all();


            /* for ($i = 0; $i < 50; $i++) { */
            $telemedpro = $telemedpros->random();
            #$patient = $patients->random();
            #$appointmentTime = Carbon::now()->addDays(rand(0, 30))->addHours(rand(0, 23))->addMinutes(rand(0, 59));
            $appointmentTime = Carbon::now()->subMonth()->addDays(rand(0, 30))->addHours(rand(0, 23))->addMinutes(rand(0, 59));
            $duration = rand(15, 120); // Duration between 15 minutes to 2 hours
            $startTime = $appointmentTime;
            $endTime = $startTime->copy()->addMinutes($duration);

            $appointment = Appointment::create([
                'telemed_pros_id' => $telemedpro->id,
                'patient_id' => $patient->id,
                'appointment_time' => $appointmentTime->toDateTimeString(),
                'in_call' => rand(0, 1),
                'meeting_id' => Str::uuid(),
                'agent_call_token' => Str::random(20),
                'patient_call_token' => Str::random(20),
                'video_token' => Str::random(20),
                'appointment_date' => $appointmentTime->toDateString(),
                'patient_email' => $patient->email,
                'patient_name' => $patient->name,
                'timezone' => 'UTC',
                'analytics' => json_encode(['metric1' => rand(0, 100), 'metric2' => rand(0, 100)]),
                'start_time' => $startTime->toDateTimeString(),
                'end_time' => $endTime->toDateTimeString(),
                'duration' => $duration
            ]);
            $statusOptions = ['delivered', 'pending'];

            $labkit = LabKit::inRandomOrder()->first();
            $cart = new Cart();
            $cart->lab_kit_id = $labkit->id;
            $cart->first_name = $patient->first_name;
            $cart->last_name = $patient->last_name;
            $cart->email = $patient->email;
            $cart->phone = $patient->phone;
            $cart->status = $statusOptions[array_rand($statusOptions)];
            $cart->date_of_birth = $patient->dob;
            $cart->patient_id = $patient->id;
            $cart->shipping_address1 = $faker->streetAddress;
            $cart->shipping_address2 = $faker->secondaryAddress;
            $cart->shipping_city = $faker->city;
            $cart->shipping_state = $faker->state;
            $cart->shipping_zipcode = $faker->postcode;
            $cart->shipping_country = $faker->country;
            $cart->billing_address1 = $faker->streetAddress;
            $cart->billing_address2 = $faker->secondaryAddress;
            $cart->billing_city = $faker->city;
            $cart->billing_state = $faker->state;
            $cart->billing_zipcode = $faker->postcode;
            $cart->billing_country = $faker->country;
            $cart->shipping_amount = $faker->randomFloat(2, 5, 20); // Random shipping amount between $5 and $20
            $cart->total_amount = $faker->randomFloat(2, 50, 200); // Random total amount between $50 and $200
            $cart->save();

            $prescription = Prescription::inRandomOrder()->first();

            PatientPrescription::create([
                'patient_id' => $patient->id,
                'appointment_id' => $appointment->id,
                'prescription_id' => $prescription->id,
                'direction_one' => $faker->sentence,
                'direction_two' => $faker->sentence,
                'dont_substitute' => rand(0, 1),
                'comments' => $faker->sentence,
                'status' => $statusOptions[array_rand($statusOptions)],
            ]);

            $addNotePatient = PatientNote::create([
                'note' => "Patient didn't send back test kit yet",
                'note_type' => "Notes",
                'patient_id' => $patient->id,
                'appointment_id' => $appointment->id,
                'telemed_pros_id' =>  $telemedpro->id
            ]);
            $category = ProfileCategory::where("category_link", 'weight_loss')->first();


            $jsonString = '{
                "weight_lb": "42",
                "height_feet": "5",
                "height_inches": "2",
                "expecting": "not_applicable",
                "evaluate_weight_loss": "yes",
                "weight_management": "no",
                "caloric_intake": "yes",
                "physical_activity": "no",
                "weightloss_goal": "yes",
                "medical_evaluation": "less_then_a_year_ago",
                "lab_tests_completed": "no",
                "comorbidities": [
                    "high_cholesterol",
                    "fatty_liver_disease"
                ],
                "chronic_pancreatitis": [
                    "none_of_the_above"
                ],
                "smoke_alcohol": null,
                "family_history_thyroid_cancer": [
                    "none_of_above_them"
                ],
                "kindney_history": [
                    "appointment_or_consultation_with",
                    "history_of_solitary_kidney_or_kidney_transplant"
                ]
            }';
            $questionBuilderData = [];
            // Convert JSON string to PHP array
            $data = json_decode($jsonString, true);
            foreach ($data as $key => $value) {
                if (is_array($value)) {
                    $value = serialize($value);
                }
                if (!empty($value)) {
                    $questionBuilderData[] = [
                        'key' => $key,
                        'value' => $value,
                        'profile_category_id' => $category->id,
                        'customer_id' => $patient->id
                    ];
                }
            }
            $questionBuilder = QuestionBuilder::insert($questionBuilderData);
        }
    }
}
