<?php

namespace Modules\Auth\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\LeaveDays;
use App\Traits\IsAPI;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\Auth\app\Models\User;
use Illuminate\Support\Str;
use Modules\Admin\app\Models\Category;
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', 'is_permanent']);
            $user = User::find($request->id);

            // Không cho chuyển từ chính thức thành lại thử việc
            if (!$request->is_permanent && $user->is_permanent) {
                return response()->json(['status' => false, 'message' => 'You cannot change an employee from permanent to probationary.']);
            }

            // Thêm ngày phép khi thành nhân viên chính thức
            if ($request->is_permanent && !$user->is_permanent) {
                $userLeaveDay = LeaveDays::where('ld_user_id', $user->id)
                    ->where('ld_year', Carbon::now()->year)
                    ->first();

                if ($userLeaveDay) {
                    $permanentCategory = Category::where('c_type', 'PERMANENT_ONLEAVE')->where('c_code', "PERMANENT")->first();
                    $permanentDefault = (int) $permanentCategory->c_value; // Ngày phép khi thành nv chính thức
                    $userLeaveDay->ld_day_total = $permanentDefault;

                    $newNote = "Cộng ngày phép cho nhân viên chính thức"; // Thêm ghi chú
                    if (!empty($userLeaveDay->ld_note)) {
                        $userLeaveDay->ld_note = $userLeaveDay->ld_note . "\n" . $newNote;
                    } else {
                        $userLeaveDay->ld_note = $newNote;
                    }
                    $userLeaveDay->save();
                }

                $payload['permanent_date'] = Carbon::now()->toDateString();
            }

            $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,
                'is_permanent' => false
            ]);

            // Khởi tạo LeaveDays cho nhân viên mới
            LeaveDays::insert([
                'ld_user_id' => $user->id,
                'ld_day_total' => 0,
                'ld_year' => Carbon::now()->year,
                'ld_additional_day' => 0,
                'ld_note' => '',
                'created_at' => now(),
                'updated_at' => now(),
            ]);

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

            if (env('APP_ENV') == 'prod' || env('APP_ENV') == 'production') {
                $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']);
            } else {
                return response()->json(['data' => ['user' => $user_res, 'gitea' => "dev", 'zulip' => "dev"], 'status' => true, 'message' => 'Create successful']);
            }
        }
    }

    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]);
    }
}
