<?php

namespace App\Http\Controllers;

use App\Models\Domain;
use App\Models\Order;
use App\Models\Script;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InstantOrderController extends Controller
{
    private $prefix = "admin/instant-orders/";
    private $resources = [];
    private $checkPermissionAndRolesController;

    function __construct(
        CheckPermissionsAndRolesController $checkPermissionAndRolesController
    ) {
        $this->resources['prefix'] = $this->prefix;
        $this->checkPermissionAndRolesController = $checkPermissionAndRolesController;
    }

    public function index(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Instant Orders']);
        $this->resources['authorized_domains'] = $this->getAuthorizedDomainList($request);
        $this->resources['scripts'] = $this->getScripts();
        return view('admin.instant-orders.index')->with($this->resources);
    }

    public function getAuthorizedDomainList($request)
    {
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query =  Domain::join('domain_authorizations', 'domains.id', 'domain_authorizations.domain_id');
            if (!$superAdmin) {
                $query->where('domain_authorizations.authorization', 1)->where('domain_authorizations.user_id', $request->user()->id);
            }
            $result = $query->select('domains.*')->get();
            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    public function getScripts()
    {
        try {
            $result = Script::all();
            return $result;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function store(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'Instant Orders']);
        $credentials = $request->validate([
            'domain_id' => ['required'],
            'imei' => ['required'],
            'script_id' => ['required']
        ]);
        if ($request->custom_link_code != null || $request->custom_link_code != "") {
            $request->validate([
                'custom_link_code' => ['min:5'],
            ]);
        }
        try {
            $storeParam = $request->except('_token', 'without_sms', 'custom_link');
            $storeParam['created_by'] = $request->user()->id;
            $storeParam['without_email'] = 0;
            $storeParam['type'] = 'sms';
            $storeParam['phone_number'] = 0;
            // $storeParam['model'] = 0;

            $settings = Setting::where('user_id', $request->user()->id)->first();
            if (isset($settings['order_settings']['link_code_length']) && $settings['order_settings']['link_code_length'] != false) {
                $length = $settings['order_settings']['link_code_length'];
            } else {
                $length = 3;
            }
            $storeParam['code'] = $this->unique_code($length);

            DB::beginTransaction();
            $order = Order::create($storeParam);
            if ($request->custom_link == '') {
                $link = $this->generateLink($request, $order, $request->custom_link_code);
            }
            DB::commit();
            // if ($request->without_email !=  "true") {
            //     $this->sendMailPhpMailer($order->id);
            // }
            $this->resources['messages'] = array("type" => "success", "description" => "Instant Order creation success");
            return redirect('admin/orders/manage')->with('messages', $this->resources);
        } catch (\Throwable $th) {
            dd($th);
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }

    function unique_code($limit)
    {
        // Ensure limit is between 3 and 20
        $limit = max(3, min(20, $limit));

        // Characters pools
        $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $lowercase = 'abcdefghijklmnopqrstuvwxyz';
        $numbers = '0123456789';

        // Shuffle and select characters
        $upper = $uppercase[mt_rand(0, strlen($uppercase) - 1)];
        $lower = $lowercase[mt_rand(0, strlen($lowercase) - 1)];
        $number = $numbers[mt_rand(0, strlen($numbers) - 1)];

        // Start with one of each type for the minimum condition
        $code = $upper . $lower . $number;

        // Combine all character sets for the remaining code
        $allCharacters = $uppercase . $lowercase . $numbers;
        $remainingLength = $limit - 3;
        for ($i = 0; $i < $remainingLength; $i++) {
            $code .= $allCharacters[mt_rand(0, strlen($allCharacters) - 1)];
        }

        // Shuffle to randomize character positions
        $code = str_shuffle($code);

        return $code;
    }

    public function generateLink($request, $order, $custom_link_code)
    {

        $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
        $query =  Domain::join('domain_authorizations', 'domains.id', 'domain_authorizations.domain_id');
        if (!$superAdmin) {
            $query->where('domain_authorizations.authorization', 1)->where('domain_authorizations.user_id', $request->user()->id);
        }
        $result = $query->where('domains.id', $order->domain_id)->select('domains.link')->first()->toArray();
        if ($custom_link_code != null) {
            $order_code = $custom_link_code;
            Order::where('id', $order->id)->update([
                'code' => $order_code,
            ]);
        } else {
            $order_code = $order->code;
        }
        if (!empty($result)) {
            $domain = $result['link'];
            // $script = Script::where('id', $order->script_id)->first();
            // $path = $script->path;
            $settings = Setting::where('user_id', $request->user()->id)->first();
            if (isset($settings['order_settings']['default_link_type']) && $settings['order_settings']['default_link_type'] != false) {
                $link = $domain . '/' . $settings['order_settings']['default_link_type'] . $order_code;
            } else {
                $link = $domain . '/' . $order_code;
            }
            Order::where('id', $order->id)->update([
                "link" => $link
            ]);
            return $link;
        } else {
            return false;
        }
    }
}
