<?php

namespace Modules\Auth\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Traits\IsAPI;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\Auth\app\Models\User;
use Illuminate\Support\Str;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UserController extends Controller
{
    use IsAPI;
    public function __construct()
    {
        $this->middleware('jwt.auth');
    }
    public function users()
    {
        return response()->json(['data' => User::all(), 'status' => true]);
    }

    public function createOrUpdate(Request $request)
    {

        $this->apiValidation($request, [
            'name' => 'required|string',
            'email' => 'required|email',
            'permission' => 'required|string',
        ]);

        if ($request->has('id')) {
            $payload = $request->only(['name', 'email', 'permission']);
            $user = User::find($request->id);

            $user->update($payload);
            return response()->json(['data' => $user, 'status' => true, 'message' => 'Update successful']);
        } else {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => bcrypt('Work@1234'),
                'permission' => $request->permission
            ]);

            $user_res = [
                'name' => $user->name,
                'email' => $user->email,
                'password' => 'Work@1234',
                'url' => 'https://ms.prology.net'
            ];

            $gitea = Http::withHeaders([
                'Authorization' => 'token ' . env('GITEA_ADMIN_TOKEN'),
                'Accept' => 'application/json',
            ])->post('https://gitea.nswteam.net/api/v1/admin/users', [
                'email' => $request->email,
                'full_name' => $request->name,
                'login_name' => Str::of($request->name)->lower()->replace(' ', ''),
                'password' => 'Work@1234',
                'must_change_password' => false,
                'send_notify' => false,
                'username' => Str::of($request->name)->lower()->replace(' ', '')
            ]);

            $gitea_data = $gitea->json();

            $gitea_res = [
                "login" => $gitea_data['login'],
                "full_name" => $gitea_data['full_name'],
                "email" => $gitea_data['email'],
                "password" => 'Work@1234',
                "url" => 'https://gitea.nswteam.net',
            ];

            $adminEmail = env('ZULIP_ADMIN_EMAIL');
            $apiKey = env('ZULIP_API_KEY');
            $apiUrl = env('ZULIP_API_URL') . '/invites';

            $zulip = Http::asForm()->withBasicAuth($adminEmail, $apiKey)->post($apiUrl, [
                'invitee_emails' => $request->email,
                'invite_expires_in_minutes' => 1440,
                'invite_as' => 400,
                'stream_ids' => '[22]'
            ]);

            $zulip_data = $zulip->json();
            $zulip_data['msg'] = 'Check inbox email ' . $request->email;
            $zulip_data['url'] = 'https://zulip.ipsupply.com.au';

            return response()->json(['data' => ['user' => $user_res, 'gitea' => $gitea_res, 'zulip' => $zulip_data], 'status' => true, 'message' => 'Create successful']);
        }

        return response()->json(['status' => false, 'message' => 'Process fail']);
    }

    public function delete(Request $request)
    {
        $user = User::find($request->id);

        if ($user) {
            $user->delete();
            return response()->json(['status' => true, 'message' => 'Delete successful']);
        }

        return response()->json(['status' => false, 'message' => 'User not found']);
    }

    public function qrcode($userId)
    {
        $user = User::find($userId);
        // Define the QR code content
        $qrCodeContent = $user->name . "\n" . $user->permission . "\n\n";

        // Define the file path
        $fileName = 'qrcode_' . $userId . '.svg';
        $filePath = 'qrcode/' . $fileName;

        if ($user) {
            if (!$user->qrcode) {
                // Generate the QR code and save it to storage
                QrCode::size(500)->margin(2)->generate($qrCodeContent, Storage::path('public/'.$filePath));
                // Update the user's record with the QR code file path
                $user->qrcode = $filePath;
                $user->save();
            }
        }

        return response()->json(['status' => true]);
    }
}
