<?php

namespace App\Http\Controllers\Web\Current\Admin;

use App\Helpers\DateHelper;
use App\Helpers\FilterHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Inertia\Inertia;

use App\Models\User;
use App\Models\DocumentConfig;
use App\Models\GeneralSettings;

use App\Helpers\SettingsHelper;
use App\Models\AppSlide;
use App\Models\PromoCode;
use App\Models\Rider;
use App\Notifications\RiderNotification;
use App\Services\ExpoService;
use App\Services\UploadService;

class SettingController extends Controller
{
    public function __construct() {}

    public function index(Request $request)
    {

        $users = User::orderBy("id", "desc")->get();

        return Inertia::render("Admin/Settings/Index", [
            'page_title' => "Users",
        ]);
    }

    public function verification_config(Request $request)
    {
        if ($request->has('create_requirement')) {
            $validator = Validator::make($request->all(), [
                'type' => 'required',
                'name' => 'required',
            ]);

            if ($validator->fails()) {
                return
                    back()
                    ->with('poperror', $validator->messages()->first());
            } else {
                $checker = DocumentConfig::where("type", strtolower($request->type))->where("name", strtolower($request->name))->first();

                if ($checker) {
                    return redirect()
                        ->back()
                        ->with('poperror', "$request->name already added");
                }

                $r = new DocumentConfig();
                $r->type =  strtolower($request->type);
                $r->name =  strtolower($request->name);
                $r->field_title =  strtolower($request->field_label);
                $r->has_upload = $request->has_upload == true ? 1 : 0;
                $r->has_two_sides_image = $request->has_two_sides_image == true ? 1 : 0;
                $r->has_field = $request->has_field == true ? 1 : 0;
                $r->is_active = $request->activated == true ? 1 : 0;

                $r->save();

                return redirect()
                    ->back()
                    ->with('popsuccess', "Record Created");
            }
        }

        if ($request->has('edit_requirement')) {
            $validator = Validator::make($request->all(), [
                'type' => 'required',
                'name' => 'required',
                'record_id' => 'required',
            ]);

            if ($validator->fails()) {
                return
                    back()
                    ->with('poperror', $validator->messages()->first());
            } else {
                $doc = DocumentConfig::find($request->record_id);

                if ($doc) {
                    $checker = DocumentConfig::where("type", strtolower($request->type))
                        ->where("name", strtolower($request->name))
                        ->where("id", "!=", $request->record_id)->first();

                    if ($checker) {
                        return redirect()
                            ->back()
                            ->with('poperror', "$request->name already added");
                    }

                    $doc->type =  strtolower($request->type);
                    $doc->name =  strtolower($request->name);
                    $doc->field_title =  strtolower($request->field_label);
                    $doc->has_upload = $request->has_upload == true ? 1 : 0;
                    $doc->has_two_sides_image = $request->has_two_sides_image == true ? 1 : 0;
                    $doc->has_field = $request->has_field == true ? 1 : 0;
                    $doc->is_active = $request->activated == true ? 1 : 0;

                    $doc->save();

                    return redirect()
                        ->back()
                        ->with('popsuccess', "Record Updated");
                }
            }
        }

        $config = DocumentConfig::orderBy("id", "desc")->get();

        return Inertia::render("Admin/Settings/BikeDocument", [
            'page_title' => "Vehicle Requirement Settings",
            'documents' => $config,
            'document_types' => ['bike', 'trike']
        ]);
    }

    public function general_settings(Request $request)
    {
        $s = GeneralSettings::where("type", "general")->get();
        $app_status_message = SettingsHelper::getObj("general", "app_status_message");
        // dd($app_status_message);

        if ($request->update_settings == true) {
            if ($request->app_status_message) {
                $app_status_message->value = $request->app_status_message;
                $app_status_message->save();
            }

            return redirect()
                ->back()
                ->with('popsuccess', "Record Updated");
        }

        return Inertia::render("Admin/Settings/General", [
            'page_title' => "General Settings",
            'settings' => $s,
            'app_status_message' => $app_status_message,
        ]);
    }

    public function trip_settings(Request $request)
    {
        $virtual_discount = SettingsHelper::getObj("trip", "virtual_discount");
        $real_discount = SettingsHelper::getObj("trip", "real_discount");
        $ride_price_per_km = SettingsHelper::getObj("trip", "ride_price_per_km");
        $fee_percentage = SettingsHelper::getObj("trip", "fee_percentage");
        $cancel_fee_percentage = SettingsHelper::getObj("trip", "cancel_fee_percentage");
        $dynamic_pricing_price = SettingsHelper::getObj("trip", "dynamic_pricing_price");
        $dynamic_pricing_date = SettingsHelper::getObj("trip", "dynamic_pricing_date");
        $trike_price_per_km = SettingsHelper::getObj("trip.trike", "ride_price_per_km");
        $trike_fee_percentage = SettingsHelper::getObj("trip.trike", "fee_percentage");
        $bonus_hour_activated = SettingsHelper::getObj("bonus_hour", "activated");
        $bonus_hour_level = SettingsHelper::getObj("bonus_hour", "level");
        $bonus_hour_start_time = SettingsHelper::getObj("bonus_hour", "start_time");
        $bonus_hour_end_time = SettingsHelper::getObj("bonus_hour", "end_time");

        $schedule_ride_price_per_km = SettingsHelper::getObj("trip.schedule", "ride_price_per_km");
        $schedule_fee_percentage = SettingsHelper::getObj("trip.schedule", "fee_percentage");
        $schedule_trike_price_per_km = SettingsHelper::getObj("trip.schedule.trike", "ride_price_per_km");
        $schedule_trike_fee_percentage = SettingsHelper::getObj("trip.schedule.trike", "fee_percentage");

        // dd($bonus_hour_activated);

        if ($request->update_settings == true) {

            $real_discount->value = $request->real_discount;
            $real_discount->save();

            $virtual_discount->value = $request->virtual_discount;
            $virtual_discount->save();

            $ride_price_per_km->value = $request->ride_price_per_km;
            $ride_price_per_km->save();

            $cancel_fee_percentage->value = $request->cancel_fee_percentage;
            $cancel_fee_percentage->save();

            $fee_percentage->value = $request->fee_percentage;
            $fee_percentage->save();

            $trike_price_per_km->value = $request->trike_price_per_km;
            $trike_price_per_km->save();

            $trike_fee_percentage->value = $request->trike_fee_percentage;
            $trike_fee_percentage->save();

            $schedule_fee_percentage->value = $request->schedule_fee_percentage;
            $schedule_fee_percentage->save();

            $schedule_ride_price_per_km->value = $request->schedule_ride_price_per_km;
            $schedule_ride_price_per_km->save();

            $schedule_trike_fee_percentage->value = $request->schedule_trike_fee_percentage;
            $schedule_trike_fee_percentage->save();

            $schedule_trike_price_per_km->value = $request->schedule_trike_price_per_km;
            $schedule_trike_price_per_km->save();

            return redirect()
                ->back()
                ->with('popsuccess', "Record Updated");
        }

        if ($request->update_dynamic_pricing == true) {
            $dynamic_pricing_price->value = $request->price;
            $dynamic_pricing_date->value = $request->date;
            $dynamic_pricing_price->save();
            $dynamic_pricing_date->save();

            return back()
                ->with('popsuccess', "Operation Successful");
        }

        if ($request->stop_dynamic_pricing == true) {
            $dynamic_pricing_price->value = null;
            $dynamic_pricing_date->value = null;
            $dynamic_pricing_price->save();
            $dynamic_pricing_date->save();

            return back()
                ->with('popsuccess', "Dynamic Pricing Stopped");
        }

        if ($request->update_bonus_hour == true) {
            $bonus_hour_activated->value = $request->bonus_hour_activated;
            $bonus_hour_level->value = $request->bonus_hour_level;

            if ($request->bonus_hour_start_time) {
                $bonus_hour_start_time->value = date("H:i", strtotime($request->bonus_hour_start_time));
            }

            if ($request->bonus_hour_end_time) {
                $bonus_hour_end_time->value = date("H:i", strtotime($request->bonus_hour_end_time));
            }

            $bonus_hour_activated->save();
            $bonus_hour_level->save();
            $bonus_hour_start_time->save();
            $bonus_hour_end_time->save();

            if ($bonus_hour_activated->value == "on") {
                (new ExpoService())->send_user_campaign("Hi, You Are in a Bonus Zone", "There are 20 riders around you, request a ride now to get 30% discount off your trip. We guarantee you a rider immediately.", []);

                $riders = Rider::whereNotNull("district_id")->get();
                foreach ($riders as $ri) {
                    $riname = ucfirst($ri->firstname);
                    $ri->notify(new RiderNotification("$riname, Bonus hour is live!", "It’s time to go online and earn money! stay online per hour and you are
guaranteed to make 500-1,000 or you get paid for staying online!", ['database', 'expo']));
                }
            }

            return back()
                ->with('popsuccess', "Bonus Hour Updated.");
        }

        return Inertia::render("Admin/Settings/Trip", [
            'page_title' => "Trip Settings",
            'virtual_discount' => $virtual_discount,
            'real_discount' => $real_discount,
            'ride_price_per_km' => $ride_price_per_km,
            'fee_percentage' => $fee_percentage,
            'cancel_fee_percentage' => $cancel_fee_percentage,
            'trike_fee_percentage' => $trike_fee_percentage,
            'dynamic_pricing_price' => $dynamic_pricing_price,
            'dynamic_pricing_date' => $dynamic_pricing_date,
            'dynamic_pricing_date_obj' => FilterHelper::dateObj($dynamic_pricing_date->value),
            'trike_price_per_km' => $trike_price_per_km,
            'bonus_hour_activated' => $bonus_hour_activated,
            'bonus_hour_level' => $bonus_hour_level,
            'bonus_hour_start_time' => $bonus_hour_start_time,
            'bonus_hour_end_time' => $bonus_hour_end_time,
            'schedule_fee_percentage' => $schedule_fee_percentage,
            'schedule_ride_price_per_km' => $schedule_ride_price_per_km,
            'schedule_trike_fee_percentage' => $schedule_trike_fee_percentage,
            'schedule_trike_price_per_km' => $schedule_trike_price_per_km,
        ]);
    }

    public function delivery_settings(Request $request)
    {
        $bs_price_per_km = SettingsHelper::getObj("delivery.bike.small", "price_per_km");
        $bm_price_per_km = SettingsHelper::getObj("delivery.bike.medium", "price_per_km");
        $bl_price_per_km = SettingsHelper::getObj("delivery.bike.large", "price_per_km");

        $ts_price_per_km = SettingsHelper::getObj("delivery.trike.small", "price_per_km");
        $tm_price_per_km = SettingsHelper::getObj("delivery.trike.medium", "price_per_km");
        $tl_price_per_km = SettingsHelper::getObj("delivery.trike.large", "price_per_km");

        $bike_fee_percentage = SettingsHelper::getObj("delivery.bike", "fee_percentage");
        $trike_fee_percentage = SettingsHelper::getObj("delivery.trike", "fee_percentage");


        if ($request->update_settings == true) {

            $bs_price_per_km->value = $request->bs_price_per_km;
            $bs_price_per_km->save();

            $bm_price_per_km->value = $request->bm_price_per_km;
            $bm_price_per_km->save();

            $bl_price_per_km->value = $request->bl_price_per_km;
            $bl_price_per_km->save();

            $ts_price_per_km->value = $request->ts_price_per_km;
            $ts_price_per_km->save();

            $tm_price_per_km->value = $request->tm_price_per_km;
            $tm_price_per_km->save();

            $tl_price_per_km->value = $request->tl_price_per_km;
            $tl_price_per_km->save();

            $bike_fee_percentage->value = $request->bike_fee_percentage;
            $bike_fee_percentage->save();

            $trike_fee_percentage->value = $request->trike_fee_percentage;
            $trike_fee_percentage->save();

            return redirect()
                ->back()
                ->with('popsuccess', "Record Updated");
        }

        return Inertia::render("Admin/Settings/Delivery", [
            'page_title' => "Delivery Settings",
            'bs_price_per_km' => $bs_price_per_km,
            'bm_price_per_km' => $bm_price_per_km,
            'bl_price_per_km' => $bl_price_per_km,
            'ts_price_per_km' => $ts_price_per_km,
            'tm_price_per_km' => $tm_price_per_km,
            'tl_price_per_km' => $tl_price_per_km,
            'bike_fee_percentage' => $bike_fee_percentage,
            'trike_fee_percentage' => $trike_fee_percentage,
        ]);
    }

    public function app_settings(Request $request)
    {

        if ($request->delete_image == true) {
            $validator = Validator::make($request->all(), [
                "image_id" => "required",
            ]);

            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->with('poperror', $validator->messages()->first());
            } else {

                $a = AppSlide::find($request->image_id);
                if ($a) {
                    $a->delete();
                }

                return back()
                    ->with('popsuccess', "Operation Successful");
            }
        }

        if ($request->upload_image == true) {
            $validator = Validator::make($request->all(), [
                "type" => "required",
                "image" => "required",
            ]);

            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->with('poperror', $validator->messages()->first());
            } else {

                if ($request->image) {
                    $fp = UploadService::upload_cloudinary($request->image->getRealPath());
                    if ($fp) {
                        $s = new AppSlide();
                        $s->type = $request->type;
                        $s->image = $fp['url'];
                        $s->save();

                        return redirect()
                            ->back()
                            ->with('popsuccess', "Upload Successful");
                    } else {
                        return redirect()
                            ->back()
                            ->with('poperror', "Upload Service Failed");
                    }
                }

                return redirect()
                    ->back()
                    ->with('poperror', "Upload Failed");
            }
        }

        return Inertia::render("Admin/Settings/App", [
            'page_title' => "App Settings",
            'rider_slides' => AppSlide::where("type", "rider")->orderBy("id", "DESC")->get(),
            'user_slides' => AppSlide::where("type", "user")->orderBy("id", "DESC")->get(),
        ]);
    }

    public function promo_codes(Request $request)
    {
        if ($request->create_promo == true) {
            $validator = Validator::make($request->all(), [
                "type" => "required",
                "name" => "required",
                "code" => "required",
                "amount_type" => "required",
                "amount" => "required",
                "max_usage" => "required",
                "starts_at" => "required",
                "ends_at" => "required",
            ]);

            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->with('poperror', $validator->messages()->first());
            } else {

                $c = PromoCode::where("code", $request->code)->first();
                if ($c) {
                    return back()
                        ->with('poperror', "$request->code already exist");
                }

                $p = new PromoCode();
                $p->name = $request->name;
                $p->type = $request->type;
                $p->code = strtolower($request->code);
                $p->amount_type = $request->amount_type;
                $p->amount = $request->amount;
                $p->max_usage = $request->max_usage;
                $p->description = $request->description;
                $p->starts_at = date("Y-m-d H:i:s", strtotime($request->starts_at));
                $p->ends_at = date("Y-m-d H:i:s", strtotime($request->ends_at));
                $p->save();

                return back()
                    ->with('popsuccess', "Operation Successful");
            }
        }

        return Inertia::render("Admin/Settings/PromoCode", [
            'page_title' => "Promo Codes",
            'promo_types' => ["ride", "delivery"],
            'promos' => PromoCode::orderBy("id", "DESC")->get(),
        ]);
    }

    public function view_promo_codes($code, Request $request)
    {
        // $uss = User::all();
        // foreach($uss as $u){
        //   if($u->real_account_balance() < 0){
        //     $b = $u->real_account_balance();
        //     echo "$u->id - $u->uuid | $b<br/><br/>";
        //   }
        // }

        // exit();

        $promo = PromoCode::where("code", strtolower($code))->first();
        if ($promo) {

            if ($request->delete_promo == true) {
                $promo->delete();

                return redirect()->route("admin.setting.promo")
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->toggle_active == true) {
                if ($promo->is_active == 0) {
                    $promo->is_active = 1;
                } else {
                    $promo->is_active = 0;
                }

                $promo->save();

                return back()
                    ->with('popsuccess', "Operation Successful");
            }

            if ($request->edit_promo == true) {
                $validator = Validator::make($request->all(), [
                    "name" => "required",
                    "amount_type" => "required",
                    "amount" => "required",
                    "max_usage" => "required",
                    "starts_at" => "required",
                    "ends_at" => "required",
                ]);

                if ($validator->fails()) {
                    return redirect()
                        ->back()
                        ->with('poperror', $validator->messages()->first());
                } else {

                    $promo->name = $request->name;
                    $promo->amount_type = $request->amount_type;
                    $promo->amount = $request->amount;
                    $promo->max_usage = $request->max_usage;
                    $promo->description = $request->description;
                    $promo->starts_at = date("Y-m-d H:i:s", strtotime($request->starts_at));
                    $promo->ends_at = date("Y-m-d H:i:s", strtotime($request->ends_at));
                    $promo->save();

                    return back()
                        ->with('popsuccess', "Operation Successful");
                }
            }

            $p =  array_diff_key($promo->toArray(), ['usage' => '']);
            $u = $promo->usage->map(function ($i) {
                return [
                    "amount" => $i->amount,
                    "user_name" => $i->user->fullname ?? "",
                    "user_id" => $i->user->id ?? "",
                    "date" => $i->created_at_obj,
                ];
            });

            return Inertia::render("Admin/Settings/PromoCodeView", [
                'page_title' => "Promo Code",
                'promo' => $p,
                'usage' => $u,
            ]);
        }
    }
}
