<?php

namespace App\Http\Controllers\api;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Profile;
use App\Models\UserSkill;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function show($id)
    {
        // DIANDROID RIBET HARUS BIKIN RESPONSE BARU
        // $user = User::with(['skills', 'profile'])->findOrFail($id);
        // return response()->json([
        //     'error' => false,
        //     'message' => 'Berhasil mengambil detail user.',
        //     'data' => new UserResource($user)
        // ], 200);

        $user = User::where('id', $id)->get();
        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil detail user.',
            'data' => UserResource::Collection($user->loadMissing(['skills', 'profile']))
        ], 200);
    }

    public function get_maids(Request $request) {
        $user = User::where('role', 3)->where('status', 2);

        $search = isset($request->search) ? $request->search : '';
        if (!empty($search)) {
            $user->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        }

        // $length = intval(isset($request->length) ? $request->length : 10);
        // $start = intval(isset($request->start) ? $request->start : 0);

        // $user = $user->skip($start)->take($length)->get();

        $user = $user->get();

        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil data.',
            'data' => UserResource::collection($user->loadMissing(['profile', 'skills']))
        ], 200);
    }


    public function admin_set_kyc(Request $request) {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'status' => 'required',
        ], [
            'required' => ':attribute harus diisi.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $update = [
            'kyc' => $request->input('status')
        ];

        $user = Profile::where('user_id', $request->input('user_id'))->first();
        $user->update($update);

        return response()->json([
            'error' => false,
            'message' => 'Status KYC diperbarui.',
            'data' => null
        ]);
    }

    public function admin_get_kyc(Request $request) {
        $user = User::select(['*','users.id'])->where('kyc', 1)->where('status', 2)->join('profiles', 'profiles.user_id', '=', 'users.id');

        $search = isset($request->search['value']) ? $request->search['value'] : '';
        if (!empty($search)) {
            $user->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        }

        $total_data = $user->count();
        $length = intval(isset($request->length) ? $request->length : 0);
        $start = intval(isset($request->start) ? $request->start : 0);

        if (!isset($request->length) || !isset($request->start)) {
            $user = $user->get();
        } else {
            $user = $user->skip($start)->take($length)->get();
        }

        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil data.',
            'data' => UserResource::collection($user->loadMissing(['profile', 'skills'])),
            'draw' => $request->draw,
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function admin_get_maids(Request $request) {
        $user = User::where('role', 3)->where('status', 2);

        $search = isset($request->search['value']) ? $request->search['value'] : '';
        if (!empty($search)) {
            $user->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        }

        $total_data = $user->count();
        $length = intval(isset($request->length) ? $request->length : 0);
        $start = intval(isset($request->start) ? $request->start : 0);

        if (!isset($request->length) || !isset($request->start)) {
            $user = $user->get();
        } else {
            $user = $user->skip($start)->take($length)->get();
        }

        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil data.',
            'data' => UserResource::collection($user->loadMissing(['profile', 'skills'])),
            'draw' => $request->draw,
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function admin_get_owners(Request $request) {
        $user = User::where('role', 2)->where('status', 2);

        $search = isset($request->search['value']) ? $request->search['value'] : '';
        if (!empty($search)) {
            $user->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        }

        $total_data = $user->count();
        $length = intval(isset($request->length) ? $request->length : 0);
        $start = intval(isset($request->start) ? $request->start : 0);

        if (!isset($request->length) || !isset($request->start)) {
            $user = $user->get();
        } else {
            $user = $user->skip($start)->take($length)->get();
        }

        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil data.',
            'data' => UserResource::collection($user->loadMissing(['profile', 'skills'])),
            'draw' => $request->draw,
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function admin_get_admins(Request $request) {
        $user = User::where('role', 1);

        $search = isset($request->search['value']) ? $request->search['value'] : '';
        if (!empty($search)) {
            $user->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        }

        $total_data = $user->count();
        $length = intval(isset($request->length) ? $request->length : 0);
        $start = intval(isset($request->start) ? $request->start : 0);

        if (!isset($request->length) || !isset($request->start)) {
            $user = $user->get();
        } else {
            $user = $user->skip($start)->take($length)->get();
        }

        return response()->json([
            'error' => false,
            'message' => 'Berhasil mengambil data.',
            'data' => UserResource::collection($user->loadMissing(['profile', 'skills'])),
            'draw' => $request->draw,
            'recordsTotal' => $total_data,
            'recordsFiltered' => $total_data,
        ], 200);
    }

    public function admin_post_admins(Request $request) {

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/|confirmed',
            'password_confirmation' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => ':attribute harus berupa email yang valid.',
            'min' => 'panjang :attribute minimal :min karakter.',
            'regex' => ':attribute harus mengandung minimal satu huruf kecil, satu huruf besar, dan satu angka.',
            'confirmed' => 'Password dan konfirmasi password tidak sama.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $cek_email = User::where('email', $request->email)->get()->count();
        if ($cek_email > 0) {
            return response()->json([
                'error' => true,
                'message' => "Email telah terpakai. Silahkan hubungi CS untuk konfirmasi jika merasa tidak mendaftar.",
                'data' => null
            ]);
        }

        $username = $this->generateUsername($request->name);

        $user = User::create([
            'role' => 1,
            'name' => $request->name,
            'username' => $username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'status' => '1'
        ]);

        return response()->json([
            'error' => false,
            'message' => 'Berhasil menambahkan admin.',
            'data' => null
        ]);
    }

    public function admin_update_admins(Request $request, $id) {

        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => ':attribute harus berupa email yang valid.',
            'min' => 'panjang :attribute minimal :min karakter.',
            'regex' => ':attribute harus mengandung minimal satu huruf kecil, satu huruf besar, dan satu angka.',
            'confirmed' => 'Password dan konfirmasi password tidak sama.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $update = [
            'name' => $request->name
        ];

        if (!empty($request->password)) {
            if ($request->password === $request->password_confirmation) {
                $update = [
                    'name' => $request->name,
                    'password' => Hash::make($request->password)
                ];
            } else {
                return response()->json([
                    'error' => true,
                    'message' => "Password dan konfirmasi password tidak sama.",
                    'data' => null
                ]);
            }
        }

        $user = User::findOrFail($id);
        $user->update($update);

        return response()->json([
            'error' => false,
            'message' => 'Berhasil merubah admin.',
            'data' => null
        ]);
    }

    public function change_password(Request $request, $id) {

        $validator = Validator::make($request->all(), [
            'password' => 'required|min:8|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/|confirmed',
            'password_confirmation' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'email' => ':attribute harus berupa email yang valid.',
            'min' => 'panjang :attribute minimal :min karakter.',
            'regex' => ':attribute harus mengandung minimal satu huruf kecil, satu huruf besar, dan satu angka.',
            'confirmed' => 'Password dan konfirmasi password tidak sama.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $update = [
            'password' => Hash::make($request->password)
        ];

        $user = User::findOrFail($id);
        $user->update($update);

        return response()->json([
            'error' => false,
            'message' => 'Berhasil merubah password.',
            'data' => null
        ]);
    }

    public function admin_delete_admins(Request $request, $id) {
        if (User::where('role', 1)->get()->count() <= 1) {
            return response()->json([
                'error' => true,
                'message' => 'Tidak bisa menghapus satu-satunya admin.',
                'data' => null
            ]);
        }

        $user = User::findOrFail($id);

        $name = $user->name;

        $user->delete();

        return response()->json([
            'error' => false,
            'message' => 'Admin '.$name.' berhasil dihapus.',
            'data' => null
        ]);
    }

    public function add_skills(Request $request, $id) {
        $validator = Validator::make($request->all(), [
            'skills' => 'required|array',
        ], [
            'required' => ':attribute harus diisi.',
            'array' => ':attribute harus berupa array.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        $user = User::find($id);
        $skills = $request->input('skills');

        $userSkills = [];
        foreach ($skills as $skill) {
            if (!empty($skill)) {
                UserSkill::create(['skill_id' => $skill, 'user_id' => $id]);
            }
        }

        return response()->json([
            'error' => false,
            'message' => 'Berhasil menambahkan skill.',
            'data' => null
        ]);
    }

    public function add_details(Request $request, $id) {
        $validator = Validator::make($request->all(), [
            'phone' => 'required',
            'address' => 'required',
            'marital_status' => 'required',
            'location' => 'required',
            'birthdate' => 'required',
            'gender' => 'required',
            'last_education' => 'required',
        ], [
            'required' => ':attribute harus diisi.',
            'array' => ':attribute harus berupa array.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        if (Carbon::parse($request->input('birthdate'))->age < 18) {
            return response()->json([
                'error' => true,
                'message' => "Anda belum cukup umur.",
                'data' => null
            ]);
        }

        $user = User::find($id);

        if ($user->role == '3') {
            if ($request->input('additional_skills', '') == '' || $request->input('desired_salary', '') == '') {
                return response()->json([
                    'error' => true,
                    'message' => "Additional Skills & Desired Salary harus diisi.",
                    'data' => null
                ]);
            }
        }

        $data = [
            'user_id' => $id,
            'image' => "/assets/img/default.png",
            'phone' => $request->input('phone'),
            'address' => $request->input('address'),
            'location' => $request->input('location'),
            'birthdate' => $request->input('birthdate'),
            'gender' => $request->input('gender'),
            'marital_status' => $request->input('marital_status'),
            'last_education' => $request->input('last_education'),
            'additional_skills' => $request->input('additional_skills', ''),
            'desired_salary' => $request->input('desired_salary', ''),
        ];

        // Check if profile exists, update if it does, create if it doesn't
        $profile = Profile::updateOrCreate(
            ['user_id' => $id],
            $data
        );

        // Update user status if needed
        $user->update(['status'=>2]);

        return response()->json([
            'error' => false,
            'message' => 'Berhasil memperbarui detail.',
            'data' => null
        ]);
    }


    public function set_image(Request $request) {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'image' => 'required|file|mimes:jpg,png,jpeg|max:5048',
        ], [
            'required' => ':attribute harus diisi.',
            'file' => ':attribute harus berupa file.',
            'mimes' => 'File :attribute harus berformat jpg, jpeg, atau png.',
            'max' => 'File :attribute tidak boleh lebih dari :max KB.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        // Upload File
        $namaimage = $this->generateRandomString(33).time();
        $ekstensiimage = $request->image->extension();

        $pathimage = '/assets/storage/document/user/image/' . $namaimage . "." . $ekstensiimage;
        $request->image->move(public_path('assets/storage/document/user/image'), $pathimage);
        // End Upload File

        $update = [
            'image' => $pathimage,
        ];

        $user = Profile::where('user_id', $request->input('user_id'))->first();
        $user->update($update);

        return response()->json([
            'error' => false,
            'message' => 'Profile berhasil diubah.',
            'data' => null
        ]);
    }

    public function verify_account(Request $request) {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'image_verif' => 'required|file|mimes:jpg,png,jpeg|max:20048',
            'ktp' => 'required|file|mimes:jpg,png,jpeg|max:20048',
        ], [
            'required' => ':attribute harus diisi.',
            'file' => ':attribute harus berupa file.',
            'mimes' => 'File :attribute harus berformat jpg, jpeg, atau png.',
            'max' => 'File :attribute tidak boleh lebih dari :max KB.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => true,
                'message' => Str::ucfirst($validator->errors()->first()),
                'data' => null
            ]);
        }

        // Upload File
        $namaimage = $this->generateRandomString(33).time();
        $ekstensiimage = $request->image_verif->extension();

        $pathimage = '/assets/storage/document/user/image/' . $namaimage . "." . $ekstensiimage;
        $request->image_verif->move(public_path('assets/storage/document/user/image'), $pathimage);

        $namaktp = $this->generateRandomString(33).time();
        $ktp = $request->ktp->extension();

        $pathktp = '/assets/storage/document/user/image/' . $namaktp . "." . $ktp;
        $request->ktp->move(public_path('assets/storage/document/user/image'), $pathktp);
        // End Upload File

        $update = [
            'image_verif' => $pathimage,
            'ktp' => $pathktp,
            'kyc' => 1,
        ];

        $user = Profile::where('user_id', $request->input('user_id'))->first();
        $user->update($update);

        return response()->json([
            'error' => false,
            'message' => 'Profile berhasil diubah.',
            'data' => null
        ]);
    }

    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    function generateUsername($name)
    {
        $cleanedName = preg_replace('/[^a-zA-Z0-9]/', '', $name);

        $cleanedName = strtolower($cleanedName);

        $randomString = Str::random(6);
        $username = $cleanedName . $randomString;

        return $username;
    }
}
