<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\AkademisiDetails;
use App\Models\InvestorDetails;
use App\Models\InvestorPersonalDetails;
use App\Models\InvestorPerusahaanDetails;
use App\Models\KomunitasDetails;
use App\Models\PemerintahDetails;
use App\Models\UmkmDetails;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    // public function store(Request $request): RedirectResponse
    // {
    //     // Validasi input
    //     $validatedData = $request->validate([
    //         'role' => ['required', 'in:pemerintah,investor,akademisi,umkm,komunitas'],
    //         'sub_sektor' => ['required', 'string'],
    //         'full_name' => ['required', 'string', 'max:255'],
    //         'nik' => ['required', 'string', 'unique:users,nik'],
    //         'birthdate' => ['required', 'date'],
    //         'address' => ['required', 'string'],
    //         'phone_number' => ['required', 'numeric'],
    //         'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
    //         'password' => ['required', 'confirmed', Rules\Password::defaults()],
    //     ]);

    //     // Buat pengguna baru
    //     $user = User::create([
    //         'role' => $validatedData['role'],
    //         'sub_sektor' => $validatedData['sub_sektor'],
    //         'full_name' => $validatedData['full_name'],
    //         'nik' => $validatedData['nik'],
    //         'birthdate' => $validatedData['birthdate'],
    //         'address' => $validatedData['address'],
    //         'phone_number' => $validatedData['phone_number'],
    //         'email' => $validatedData['email'],
    //         'password' => Hash::make($validatedData['password']),
    //     ]);

    //     event(new Registered($user));

    //     Auth::login($user);

    //     // Set flash message
    //     session()->flash('status', 'Registration successful!');

    //     // Redirect berdasarkan role pengguna
    //     switch ($user->role) {
    //         case 'pemerintah':
    //             return redirect()->route('pemerintah.dashboard');
    //         case 'investor':
    //             return redirect()->route('investor.dashboard');
    //         case 'akademisi':
    //             return redirect()->route('akademisi.dashboard');
    //         case 'umkm':
    //             return redirect()->route('umkm.dashboard');
    //         case 'komunitas':
    //             return redirect()->route('komunitas.dashboard');
    //         default:
    //             return redirect(RouteServiceProvider::HOME);
    //     }
    // }


    // public function store(Request $request): RedirectResponse
    // {
    //     // Validasi input
    //     $validatedData = $request->validate([
    //         'role' => ['required', 'in:pemerintah,investor,akademisi,umkm,komunitas'],
    //         'sub_sektor' => ['required', 'string'],
    //         'full_name' => ['required', 'string', 'max:255'],
    //         'nik' => ['required', 'string', 'unique:users,nik'],
    //         'birthdate' => ['required', 'date'],
    //         'address' => ['required', 'string'],
    //         'phone_number' => ['required', 'string'], // Adjust validation based on your phone number format
    //         'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
    //         'password' => ['required', 'confirmed', Rules\Password::defaults()],
    //     ]);

    //     // Proses upload foto jika ada
    //     $foto = $request->file('foto')
    //         ? $request->file('foto')->storeAs('foto', $request->file('foto')->getClientOriginalName(), 'public')
    //         : null;

    //     // Buat pengguna baru
    //     $user = User::create([
    //         'role' => $validatedData['role'],
    //         'sub_sektor' => $validatedData['sub_sektor'],
    //         'full_name' => $validatedData['full_name'],
    //         'nik' => $validatedData['nik'],
    //         'birthdate' => $validatedData['birthdate'],
    //         'address' => $validatedData['address'],
    //         'phone_number' => $validatedData['phone_number'],
    //         'email' => $validatedData['email'],
    //         'password' => Hash::make($validatedData['password']),
    //     ]);

    //     event(new Registered($user));

    //     Auth::login($user);
    //     // Handle role-specific details
    //     switch ($user->role) {
    //         case 'pemerintah':
    //             PemerintahDetails::create([
    //                 'user_id' => $user->id,
    //                 'institution_name' => $request->input('institution_name'),
    //                 'foto' => $foto,
    //                 'description' => $request->input('description'),
    //             ]);
    //             return redirect()->route('pemerintah.dashboard');

    //         case 'umkm':
    //             UmkmDetails::create([
    //                 'user_id' => $user->id,
    //                 'umkm_name' => $request->input('umkm_name'),
    //                 'foto' => $request->input('foto'),
    //                 'establishment_date' => $request->input('establishment_date'),
    //                 'description' => $request->input('description'),
    //                 'product' => $request->input('product'),
    //                 'siup_number' => $request->input('siup_number'),
    //                 'profit' => $request->input('profit'),
    //             ]);
    //             return redirect()->route('umkm.dashboard');

    //         case 'investor':
    //             $investorDetail = InvestorDetails::create([
    //                 'user_id' => $user->id,
    //                 'category' => $request->input('category'),
    //             ]);

    //             if ($request->input('category') == 'personal') {
    //                 InvestorPersonalDetails::create([
    //                     'investor_details_id' => $investorDetail->id,
    //                     'npwp_number' => $request->input('npwp_number'),
    //                     'job' => $request->input('job'),
    //                     'total_assets' => $request->input('total_assets'),
    //                 ]);
    //             } elseif ($request->input('category') == 'perusahaan') {
    //                 InvestorPerusahaanDetails::create([
    //                     'investor_details_id' => $investorDetail->id,
    //                     'company_name' => $request->input('company_name'),
    //                     'foto' => $request->input('foto'),
    //                     'establishment_date' => $request->input('establishment_date'),
    //                     'description' => $request->input('description'),
    //                     'npwp_number' => $request->input('npwp_number'),
    //                     'siup_number' => $request->input('siup_number'),
    //                     'nib_number' => $request->input('nib_number'),
    //                 ]);
    //             }
    //             return redirect()->route('investor.dashboard');

    //         case 'akademisi':
    //             AkademisiDetails::create([
    //                 'user_id' => $user->id,
    //                 'university_name' => $request->input('university_name'),
    //                 'foto' => $request->input('foto'),
    //                 'description' => $request->input('description'),
    //                 'faculty' => $request->input('faculty'),
    //                 'study_program' => $request->input('study_program'),
    //                 'expertise_field' => $request->input('expertise_field'),
    //             ]);
    //             return redirect()->route('akademisi.dashboard');

    //         case 'komunitas':
    //             KomunitasDetails::create([
    //                 'user_id' => $user->id,
    //                 'community_name' => $request->input('community_name'),
    //                 'foto' => $request->input('foto'),
    //                 'establishment_date' => $request->input('establishment_date'),
    //                 'description' => $request->input('description'),
    //                 'community_license' => $request->input('community_license'),
    //             ]);
    //             return redirect()->route('komunitas.dashboard');

    //         default:
    //             return redirect(RouteServiceProvider::HOME);
    //     }
    // }

    // public function store(Request $request): RedirectResponse
    // {
    //     // Validate common input fields
    //     $validatedData = $request->validate([
    //         'role' => ['required', 'in:pemerintah,investor,akademisi,umkm,komunitas'],
    //         'sub_sektor' => ['required', 'string'],
    //         'full_name' => ['required', 'string', 'max:255'],
    //         'nik' => ['required', 'string', 'unique:users,nik'],
    //         'birthdate' => ['required', 'date'],
    //         'address' => ['required', 'string'],
    //         'phone_number' => ['required', 'string'], // Adjust validation based on your phone number format
    //         'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
    //         'password' => ['required', 'confirmed', Rules\Password::defaults()],
    //         // 'category' => ['nullable', 'string'],
    //     ]);

    //     // Additional validation based on role
    //     $roleSpecificRules = [];
    //     switch ($validatedData['role']) {
    //         case 'pemerintah':
    //             $roleSpecificRules = [
    //                 'institution_name' => ['required', 'string'],
    //                 'description_pemerintah' => ['required', 'string'],
    //             ];
    //             break;

    //         case 'umkm':
    //             $roleSpecificRules = [
    //                 'umkm_name' => ['required', 'string'],
    //                 'establishment_date_umkm' => ['required', 'date'],
    //                 'description_umkm' => ['required', 'string'],
    //                 'product' => ['required', 'string'],
    //                 'siup_number_umkm' => ['required', 'string'],
    //                 'profit_umkm' => ['required', 'numeric'],
    //             ];
    //             break;

    //             // case 'investor':
    //             //     $roleSpecificRules = [
    //             //         'category' => ['required', 'in:personal,perusahaan'],
    //             //         'npwp_number_inves_personal' => ['required', 'string'],
    //             //         'npwp_number_inves_perusahaan' => ['required', 'string'],
    //             //         'job' => ['required', 'string'],
    //             //         'total_assets' => ['required', 'numeric'],
    //             //         'company_name' => ['required', 'string'],
    //             //         'siup_number_inves_perusahaan' => ['required', 'string'],
    //             //         'nib_number' => ['required', 'string'],
    //             //         'establishment_date_inves_perusahaan' => ['required', 'date'],
    //             //         'description_inves_perusahaan' => ['required', 'string'],
    //             //         'profit_inves_personal' => ['required', 'numeric'],
    //             //     ];
    //             //     break;

    //         case 'investor':
    //             // Common validation rules for all investor categories
    //             $commonRules = [
    //                 'category' => ['required', 'string'],
    //             ];

    //             // Validate the common rules first
    //             $validatedData = $request->validate($commonRules);

    //             // Role-specific validation rules based on category
    //             $roleSpecificRules = [];
    //             switch ($validatedData['category']) {
    //                 case 'personal':
    //                     $roleSpecificRules = [
    //                         'npwp_number_inves_personal' => ['required', 'string'],
    //                         'job' => ['required', 'string'],
    //                         'total_assets' => ['required', 'numeric'],
    //                         'profit_inves_personal' => ['required', 'numeric'],
    //                     ];
    //                     break;

    //                 case 'perusahaan':
    //                     $roleSpecificRules = [
    //                         'company_name' => ['required', 'string'],
    //                         'establishment_date_inves_perusahaan' => ['required', 'date'],
    //                         'description_inves_perusahaan' => ['required', 'string'],
    //                         'npwp_number_inves_perusahaan' => ['required', 'string'],
    //                         'siup_number_inves_perusahaan' => ['required', 'string'],
    //                         'nib_number' => ['required', 'string'],
    //                         'profit_inves_perusahaan' => ['required', 'numeric'],
    //                     ];
    //                     break;

    //                 default:
    //                     // Handle invalid category if necessary
    //                     return response()->json(['error' => 'Invalid investor category'], 400);
    //             }

    //             // Validate the role-specific rules
    //             $request->validate($roleSpecificRules);
    //             break;


    //         case 'akademisi':
    //             $roleSpecificRules = [
    //                 'university_name' => ['required', 'string'],
    //                 'faculty' => ['required', 'string'],
    //                 'description_akademisi' => ['required', 'string'],
    //                 'study_program' => ['required', 'string'],
    //                 'expertise_field' => ['required', 'string'],
    //             ];
    //             break;

    //         case 'komunitas':
    //             $roleSpecificRules = [
    //                 'community_name' => ['required', 'string'],
    //                 'establishment_date_komunitas' => ['required', 'date'],
    //                 'description_komunitas' => ['required', 'string'],
    //                 'community_license' => ['required', 'string'],
    //             ];
    //             break;
    //     }

    //     // Apply role-specific validation rules
    //     if (!empty($roleSpecificRules)) {
    //         $request->validate($roleSpecificRules);
    //     }

    //     // dd($request->all());


    //     // Process file upload
    //     $fotoPath = null;
    //     if ($request->hasFile('foto')) {
    //         $foto = $request->file('foto');
    //         $fotoPath = $foto->storeAs('foto', $foto->getClientOriginalName(), 'public');
    //     }

    //     // Create new user
    //     $user = User::create([
    //         'role' => $validatedData['role'],
    //         'sub_sektor' => $validatedData['sub_sektor'],
    //         'full_name' => $validatedData['full_name'],
    //         'nik' => $validatedData['nik'],
    //         'birthdate' => $validatedData['birthdate'],
    //         'address' => $validatedData['address'],
    //         'phone_number' => $validatedData['phone_number'],
    //         'email' => $validatedData['email'],
    //         'password' => Hash::make($validatedData['password']),
    //     ]);

    //     event(new Registered($user));
    //     Auth::login($user);

    //     // Handle role-specific details
    //     switch ($user->role) {
    //         case 'pemerintah':
    //             PemerintahDetails::create([
    //                 'user_id' => $user->id,
    //                 'institution_name' => $request->input('institution_name'),
    //                 'foto' => $fotoPath,
    //                 'description_pemerintah' => $request->input('description_pemerintah'),
    //             ]);
    //             return redirect()->route('pemerintah.dashboard');

    //         case 'umkm':
    //             UmkmDetails::create([
    //                 'user_id' => $user->id,
    //                 'umkm_name' => $request->input('umkm_name'),
    //                 'foto' => $fotoPath,
    //                 'establishment_date_umkm' => $request->input('establishment_date_umkm'),
    //                 'description_umkm' => $request->input('description_umkm'),
    //                 'product' => $request->input('product'),
    //                 'siup_number_umkm' => $request->input('siup_number_umkm'),
    //                 'profit_umkm' => $request->input('profit_umkm'),
    //             ]);
    //             return redirect()->route('umkm.dashboard');

    //         case 'investor':
    //             $investorDetail = InvestorDetails::create([
    //                 'user_id' => $user->id,
    //                 'foto' => $fotoPath,
    //                 'category' => $request->input('category'),
    //             ]);

    //             if ($request->input('category') == 'personal') {
    //                 InvestorPersonalDetails::create([
    //                     'investor_details_id' => $investorDetail->id,
    //                     // 'foto' => $fotoPath,
    //                     'npwp_number_inves_personal' => $request->input('npwp_number_inves_personal'),
    //                     'job' => $request->input('job'),
    //                     'total_assets' => $request->input('total_assets'),
    //                     'profit_inves_personal' => $request->input('profit_inves_personal'),
    //                 ]);
    //             } elseif ($request->input('category') == 'perusahaan') {
    //                 InvestorPerusahaanDetails::create([
    //                     'investor_details_id' => $investorDetail->id,
    //                     'company_name' => $request->input('company_name'),
    //                     // 'foto' => $fotoPath,
    //                     'establishment_date_inves_perusahaan' => $request->input('establishment_date_inves_perusahaan'),
    //                     'description_inves_perusahaan' => $request->input('description_inves_perusahaan'),
    //                     'npwp_number_inves_perusahaan' => $request->input('npwp_number_inves_perusahaan'),
    //                     'siup_number_inves_perusahaan' => $request->input('siup_number_inves_perusahaan'),
    //                     'nib_number' => $request->input('nib_number'),
    //                     'profit_inves_perusahaan' => $request->input('profit_inves_perusahaan'),
    //                 ]);
    //             }
    //             return redirect()->route('investor.dashboard');

    //         case 'akademisi':
    //             AkademisiDetails::create([
    //                 'user_id' => $user->id,
    //                 'university_name' => $request->input('university_name'),
    //                 'foto' => $fotoPath,
    //                 'description_akademisi' => $request->input('description_akademisi'),
    //                 'faculty' => $request->input('faculty'),
    //                 'study_program' => $request->input('study_program'),
    //                 'expertise_field' => $request->input('expertise_field'),
    //             ]);
    //             return redirect()->route('akademisi.dashboard');

    //         case 'komunitas':
    //             KomunitasDetails::create([
    //                 'user_id' => $user->id,
    //                 'community_name' => $request->input('community_name'),
    //                 'foto' => $fotoPath,
    //                 'establishment_date_komunitas' => $request->input('establishment_date_komunitas'),
    //                 'description_komunitas' => $request->input('description_komunitas'),
    //                 'community_license' => $request->input('community_license'),
    //             ]);
    //             return redirect()->route('komunitas.dashboard');

    //         default:
    //             return redirect(RouteServiceProvider::HOME);
    //     }
    // }


    public function store(Request $request): RedirectResponse
    {
        // Define common rules
        $commonRules = [
            'role' => ['required', 'in:pemerintah,investor,akademisi,umkm,komunitas'],
            // 'sub_sektor' => ['required', 'string'],
            // 'sub_sektor' => 'required|array',
            // 'sub_sektor.*' => 'string',
            'full_name' => ['required', 'string', 'max:255'],
            'nik' => ['required', 'string', 'unique:users,nik'],
            'birthdate' => ['required', 'date'],
            'address' => ['required', 'string'],
            'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'phone_number' => ['required', 'string'], // Adjust validation based on your phone number format
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ];

        // Validate the common rules first
        $validatedData = $request->validate($commonRules);

        // Role-specific validation rules based on role and category
        $roleSpecificRules = [];

        switch ($validatedData['role']) {
            case 'pemerintah':
                $roleSpecificRules = [
                    'institution_name' => ['required', 'string'],
                    'description_pemerintah' => ['required', 'string'],
                ];
                break;

            case 'umkm':
                $roleSpecificRules = [
                    'umkm_name' => ['required', 'string'],
                    'establishment_date_umkm' => ['required', 'date'],
                    'description_umkm' => ['required', 'string'],
                    'product' => ['required', 'string'],
                    'laporan_keuangan' => 'required|file|mimes:pdf,doc,docx',
                    'siup_number_umkm' => ['required', 'string'],
                    'profit_umkm' => ['required', 'string'],
                    'pirt' => ['nullable', 'string'],
                    'sertifikat_halal_mui' => 'nullable|file|mimes:pdf,doc,docx',
                    'bpom' => ['nullable', 'string'],
                ];
                break;

            case 'investor':
                // Ensure 'category' is provided and validated
                $request->validate([
                    'category' => ['required', 'in:personal,perusahaan'],
                ]);

                // Assign role-specific rules based on category
                switch ($request->input('category')) {
                    case 'personal':
                        $roleSpecificRules = [
                            'npwp_number_inves_personal' => ['required', 'string'],
                            'job' => ['required', 'string'],
                            'total_assets' => ['required', 'numeric'],
                            'profit_inves_personal' => ['required', 'numeric'],
                        ];
                        break;

                    case 'perusahaan':
                        $roleSpecificRules = [
                            'company_name' => ['required', 'string'],
                            'establishment_date_inves_perusahaan' => ['required', 'date'],
                            'description_inves_perusahaan' => ['required', 'string'],
                            'npwp_number_inves_perusahaan' => ['required', 'string'],
                            'siup_number_inves_perusahaan' => ['required', 'string'],
                            'nib_number' => ['required', 'string'],
                            'profit_inves_perusahaan' => ['required', 'numeric'],
                        ];
                        break;

                    default:
                        return response()->json(['error' => 'Invalid investor category'], 400);
                }
                break;

            case 'akademisi':
                $roleSpecificRules = [
                    'university_name' => ['required', 'string'],
                    'faculty' => ['required', 'string'],
                    'description_akademisi' => ['required', 'string'],
                    'study_program' => ['required', 'string'],
                    'expertise_field' => ['required', 'string'],
                ];
                break;

            case 'komunitas':
                $roleSpecificRules = [
                    'community_name' => ['required', 'string'],
                    'establishment_date_komunitas' => ['required', 'date'],
                    'description_komunitas' => ['required', 'string'],
                    'community_license' => ['required', 'string'],
                ];
                break;

            default:
                return response()->json(['error' => 'Invalid role'], 400);
        }

        // Apply role-specific rules if any
        if (!empty($roleSpecificRules)) {
            $request->validate($roleSpecificRules);
        }

        // // Handle file upload
        // $fotoPath = null;
        // if ($request->hasFile('foto')) {
        //     $foto = $request->file('foto');
        //     $fotoPath = $foto->storeAs('foto', $foto->getClientOriginalName(), 'public');
        // }

        // // Handle file uploads
        // $laporan_keuangan = $request->file('laporan_keuangan')
        //     ? $request->file('laporan_keuangan')->storeAs('laporan_keuangan', $request->file('laporan_keuangan')->getClientOriginalName(), 'public')
        //     : null;

        // // Handle file upload
        // $sertifikat_halal_mui = $request->file('sertifikat_halal_mui')
        // ? $request->file('sertifikat_halal_mui')->storeAs('sertifikat_halal_mui', $request->file('sertifikat_halal_mui')->getClientOriginalName(), 'public')
        // : null;

        // Handle file upload
        $fotoPath = null;
        if ($request->hasFile('foto')) {
            $foto = $request->file('foto');
            // Menghasilkan nama file unik dengan timestamp
            $uniqueFotoName = time() . '_' . $foto->getClientOriginalName();
            $fotoPath = $foto->storeAs('foto', $uniqueFotoName, 'public');
        }

        // Handle laporan keuangan upload
        $laporan_keuangan_path = null; // Inisialisasi path untuk laporan keuangan
        if ($request->hasFile('laporan_keuangan')) {
            $laporan_keuangan = $request->file('laporan_keuangan');
            // Menghasilkan nama file unik untuk laporan keuangan
            $uniqueLaporanKeuanganName = time() . '_' . $laporan_keuangan->getClientOriginalName();
            $laporan_keuangan_path = $laporan_keuangan->storeAs('laporan_keuangan', $uniqueLaporanKeuanganName, 'public');
        }

        // Handle sertifikat halal MUI upload
        $sertifikat_halal_mui_path = null; // Inisialisasi path untuk sertifikat halal MUI
        if ($request->hasFile('sertifikat_halal_mui')) {
            $sertifikat_halal_mui = $request->file('sertifikat_halal_mui');
            // Menghasilkan nama file unik untuk sertifikat halal MUI
            $uniqueSertifikatHalalName = time() . '_' . $sertifikat_halal_mui->getClientOriginalName();
            $sertifikat_halal_mui_path = $sertifikat_halal_mui->storeAs('sertifikat_halal_mui', $uniqueSertifikatHalalName, 'public');
        }


        // Create new user
        $user = User::create([
            'role' => $validatedData['role'],
            // 'sub_sektor' => $validatedData['sub_sektor'],
            // 'sub_sektor' => implode(',', $validatedData['sub_sektor']), // Simpan sebagai string
            'full_name' => $validatedData['full_name'],
            'nik' => $validatedData['nik'],
            'birthdate' => $validatedData['birthdate'],
            'address' => $validatedData['address'],
            'phone_number' => $validatedData['phone_number'],
            'email' => $validatedData['email'],
            'password' => Hash::make($validatedData['password']),
        ]);

        event(new Registered($user));
        Auth::login($user);

        // Handle role-specific details
        switch ($user->role) {
            case 'pemerintah':
                PemerintahDetails::create([
                    'user_id' => $user->id,
                    'institution_name' => $request->input('institution_name'),
                    'foto' => $fotoPath,
                    'description_pemerintah' => $request->input('description_pemerintah'),
                ]);
                return redirect()->route('pemerintah.dashboard');

            case 'umkm':
                UmkmDetails::create([
                    'user_id' => $user->id,
                    'umkm_name' => $request->input('umkm_name'),
                    'foto' => $fotoPath,
                    'establishment_date_umkm' => $request->input('establishment_date_umkm'),
                    'description_umkm' => $request->input('description_umkm'),
                    'product' => $request->input('product'),
                    'laporan_keuangan' => $laporan_keuangan_path,
                    'siup_number_umkm' => $request->input('siup_number_umkm'),
                    'profit_umkm' => $request->input('profit_umkm'),
                    'pirt' => $request->input('pirt'),  // Tambahkan pirt
                    'sertifikat_halal_mui' => $sertifikat_halal_mui_path,  // Tambahkan sertifikat halal mui
                    'bpom' => $request->input('bpom'),  // Tambahkan bpom
                ]);
                return redirect()->route('umkm.dashboard');

            case 'investor':
                $investorDetail = InvestorDetails::create([
                    'user_id' => $user->id,
                    'foto' => $fotoPath,
                    'category' => $request->input('category'),
                ]);

                if ($request->input('category') == 'personal') {
                    InvestorPersonalDetails::create([
                        'investor_details_id' => $investorDetail->id,
                        'npwp_number_inves_personal' => $request->input('npwp_number_inves_personal'),
                        'job' => $request->input('job'),
                        'total_assets' => $request->input('total_assets'),
                        'profit_inves_personal' => $request->input('profit_inves_personal'),
                    ]);
                } elseif ($request->input('category') == 'perusahaan') {
                    InvestorPerusahaanDetails::create([
                        'investor_details_id' => $investorDetail->id,
                        'company_name' => $request->input('company_name'),
                        'establishment_date_inves_perusahaan' => $request->input('establishment_date_inves_perusahaan'),
                        'description_inves_perusahaan' => $request->input('description_inves_perusahaan'),
                        'npwp_number_inves_perusahaan' => $request->input('npwp_number_inves_perusahaan'),
                        'siup_number_inves_perusahaan' => $request->input('siup_number_inves_perusahaan'),
                        'nib_number' => $request->input('nib_number'),
                        'profit_inves_perusahaan' => $request->input('profit_inves_perusahaan'),
                    ]);
                }
                return redirect()->route('investor.dashboard');

            case 'akademisi':
                AkademisiDetails::create([
                    'user_id' => $user->id,
                    'university_name' => $request->input('university_name'),
                    'foto' => $fotoPath,
                    'description_akademisi' => $request->input('description_akademisi'),
                    'faculty' => $request->input('faculty'),
                    'study_program' => $request->input('study_program'),
                    'expertise_field' => $request->input('expertise_field'),
                ]);
                return redirect()->route('akademisi.dashboard');

            case 'komunitas':
                KomunitasDetails::create([
                    'user_id' => $user->id,
                    'community_name' => $request->input('community_name'),
                    'foto' => $fotoPath,
                    'establishment_date_komunitas' => $request->input('establishment_date_komunitas'),
                    'description_komunitas' => $request->input('description_komunitas'),
                    'community_license' => $request->input('community_license'),
                ]);
                return redirect()->route('komunitas.dashboard');

            default:
                return response()->json(['error' => 'Invalid role'], 400);
        }
    }

    public function edit($id)
    {
        $data = User::find($id);

        if (!$data) {
            return redirect()->route('profile.show')->with('error', 'Project not found');
        }

        $relatedData = null;
        switch ($data->role) {
            case 'pemerintah':
                $relatedData = $data->pemerintahDetails;
                break;
            case 'umkm':
                $relatedData = $data->umkmDetails;
                break;
            case 'akademisi':
                $relatedData = $data->akademisiDetails;
                break;
            case 'investor':
                $relatedData = $data->investorDetails;
                break;
            case 'komunitas':
                $relatedData = $data->komunitasDetails;
                break;
        }

        return view('profile.edit', compact('data', 'relatedData'));
    }


    public function update(Request $request, $id): RedirectResponse
    {
        // Find the user by ID
        $user = User::findOrFail($id);

        // Define common rules
        $rules = [
            'role' => ['required', 'in:pemerintah,investor,akademisi,umkm,komunitas'],
            // 'sub_sektor' => 'required|array',
            // 'sub_sektor.*' => 'string',
            'full_name' => ['required', 'string', 'max:255'],
            'nik' => ['required', 'string', 'unique:users,nik,' . $user->id],
            'birthdate' => ['required', 'date'],
            'address' => ['required', 'string'],
            'phone_number' => ['required', 'string'],
            'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,' . $user->id],
            'password' => ['nullable', 'confirmed', Rules\Password::defaults()], // Allow password to be nullable
        ];

        switch ($request->input('kategori', $user->role)) {
            case 'pemerintah':
                $rules = array_merge($rules, [
                    'institution_name' => ['required', 'string'],
                    'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                    'description_pemerintah' => ['required', 'string'],
                ]);
                break;

            case 'umkm':
                $rules = array_merge($rules, [
                    'umkm_name' => ['required', 'string'],
                    'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                    'establishment_date_umkm' => ['required', 'date'],
                    'description_umkm' => ['required', 'string'],
                    'product' => ['required', 'string'],
                    'laporan_keuangan' => 'nullable|file|mimes:pdf,doc,docx',
                    'siup_number_umkm' => ['required', 'string'],
                    'profit_umkm' => ['required', 'string'],
                    'pirt' => ['nullable', 'string'],
                    'sertifikat_halal_mui' => ['nullable|file|mimes:pdf,doc,docx'],
                    'bpom' => ['nullable', 'string'],
                ]);
                break;

            case 'investor':
                // Ensure 'category' is provided and validated
                $request->validate([
                    'category' => ['required', 'in:personal,perusahaan'],
                    'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                ]);

                // Assign role-specific rules based on category
                switch ($request->input('category')) {
                    case 'personal':
                        $rules = array_merge($rules, [
                            'npwp_number_inves_personal' => ['required', 'string'],
                            'job' => ['required', 'string'],
                            'total_assets' => ['required', 'numeric'],
                            'profit_inves_personal' => ['required', 'numeric'],
                        ]);
                        break;

                    case 'perusahaan':
                        $rules = array_merge($rules, [
                            'company_name' => ['required', 'string'],
                            'establishment_date_inves_perusahaan' => ['required', 'date'],
                            'description_inves_perusahaan' => ['required', 'string'],
                            'npwp_number_inves_perusahaan' => ['required', 'string'],
                            'siup_number_inves_perusahaan' => ['required', 'string'],
                            'nib_number' => ['required', 'string'],
                            'profit_inves_perusahaan' => ['required', 'numeric'],
                        ]);
                        break;

                    default:
                        return response()->json(['error' => 'Invalid investor category'], 400);
                }
                break;

            case 'akademisi':
                $rules = array_merge($rules, [
                    'university_name' => ['required', 'string'],
                    'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                    'faculty' => ['required', 'string'],
                    'description_akademisi' => ['required', 'string'],
                    'study_program' => ['required', 'string'],
                    'expertise_field' => ['required', 'string'],
                ]);
                break;

            case 'komunitas':
                $rules = array_merge($rules, [
                    'community_name' => ['required', 'string'],
                    'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                    'establishment_date_komunitas' => ['required', 'date'],
                    'description_komunitas' => ['required', 'string'],
                    'community_license' => ['required', 'string'],
                ]);
                break;

            default:
                return response()->json(['error' => 'Invalid role'], 400);
        }

        // Validate the request data
        $validatedData = $request->validate($rules);


        // Check if a new password is provided
        if ($request->filled('password')) {
            // Hash the new password
            $validatedData['password'] = Hash::make($validatedData['password']);
        } else {
            // Remove password from the validated data array if not provided
            unset($validatedData['password']);
        }

        // Update the main project data
        $user->update($validatedData);


        // Handle role-specific details update
        switch ($request->input('role', $user->role)) {
            case 'pemerintah':
                // Prepare the data to update or create
                $dataToUpdate = $request->only([
                    'institution_name',
                    'description_pemerintah',
                ]);

                // Handle the file upload if there is a file
                // if ($request->hasFile('foto')) {
                //     $dataToUpdate['foto'] = $request->file('foto')->storeAs(
                //         'foto',
                //         $request->file('foto')->getClientOriginalName(),
                //         'public'
                //     );
                // }

                // Handle the file upload if there is a file
                if ($request->hasFile('foto')) {
                    $foto = $request->file('foto');

                    // Generate a unique file name using timestamp and original file name
                    $uniqueFileName = time() . '_' . $foto->getClientOriginalName();

                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['foto'] = $foto->storeAs('foto', $uniqueFileName, 'public');
                }

                // Update or create the pemerintah details
                $user->pemerintahDetails()->updateOrCreate(
                    ['user_id' => $user->id],
                    $dataToUpdate
                );
                break;

            case 'umkm':
                // Prepare the data to update or create
                $dataToUpdate = $request->only([
                    'umkm_name',
                    'establishment_date_umkm',
                    'description_umkm',
                    'product',
                    'siup_number_umkm',
                    'profit_umkm',
                    'pirt',  // Tambahkan pirt
                    'bpom',  // Tambahkan bpom
                ]);

                // Handle the file upload for 'foto' if there is a file
                // if ($request->hasFile('foto')) {
                //     $dataToUpdate['foto'] = $request->file('foto')->storeAs(
                //         'foto',
                //         $request->file('foto')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $dataToUpdate['foto'] = $user->umkmDetails->foto; // Keep existing photo if not uploaded
                // }

                // Handle the file upload for 'laporan_keuangan' if there is a file
                // if ($request->hasFile('laporan_keuangan')) {
                //     $dataToUpdate['laporan_keuangan'] = $request->file('laporan_keuangan')->storeAs(
                //         'laporan_keuangan',
                //         $request->file('laporan_keuangan')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $dataToUpdate['laporan_keuangan'] = $user->umkmDetails->laporan_keuangan; // Keep existing laporan if not uploaded
                // }

                // Handle the file upload for 'sertifikat_halal_mui' if there is a file
                // if ($request->hasFile('sertifikat_halal_mui')) {
                //     $dataToUpdate['sertifikat_halal_mui'] = $request->file('sertifikat_halal_mui')->storeAs(
                //         'sertifikat_halal_mui',
                //         $request->file('sertifikat_halal_mui')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $dataToUpdate['sertifikat_halal_mui'] = $user->umkmDetails->sertifikat_halal_mui; // Keep existing sertifikat if not uploaded
                // }

                // Handle the file upload for 'foto'
                if ($request->hasFile('foto')) {
                    $foto = $request->file('foto');

                    // Generate a unique file name
                    $uniqueFotoName = time() . '_' . $foto->getClientOriginalName();

                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['foto'] = $foto->storeAs('foto', $uniqueFotoName, 'public');
                } else {
                    // Keep existing photo if not uploaded
                    $dataToUpdate['foto'] = $user->umkmDetails->foto;
                }

                // Handle the file upload for 'laporan_keuangan'
                if ($request->hasFile('laporan_keuangan')) {
                    $laporanKeuangan = $request->file('laporan_keuangan');

                    // Generate a unique file name
                    $uniqueLaporanName = time() . '_' . $laporanKeuangan->getClientOriginalName();

                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['laporan_keuangan'] = $laporanKeuangan->storeAs('laporan_keuangan', $uniqueLaporanName, 'public');
                } else {
                    // Keep existing laporan if not uploaded
                    $dataToUpdate['laporan_keuangan'] = $user->umkmDetails->laporan_keuangan;
                }

                // Handle the file upload for 'sertifikat_halal_mui'
                if ($request->hasFile('sertifikat_halal_mui')) {
                    $sertifikatHalal = $request->file('sertifikat_halal_mui');

                    // Generate a unique file name
                    $uniqueSertifikatName = time() . '_' . $sertifikatHalal->getClientOriginalName();

                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['sertifikat_halal_mui'] = $sertifikatHalal->storeAs('sertifikat_halal_mui', $uniqueSertifikatName, 'public');
                } else {
                    // Keep existing sertifikat if not uploaded
                    $dataToUpdate['sertifikat_halal_mui'] = $user->umkmDetails->sertifikat_halal_mui;
                }

                // Update or create the UMKM details
                $user->umkmDetails()->updateOrCreate(
                    ['user_id' => $user->id],
                    $dataToUpdate
                );
                break;


            case 'investor':
                // Update or create the main investor details
                $investorDetail = $user->investorDetails()->updateOrCreate(
                    ['user_id' => $user->id],
                    $request->only([
                        'category' => $request->input('category'),
                    ])
                );

                // // Handle the file upload if there is a file
                // if ($request->hasFile('foto')) {
                //     $investorDetail->foto = $request->file('foto')->storeAs(
                //         'foto',
                //         $request->file('foto')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $investorDetail->foto = $user->investorDetails->foto; // Keep existing photo if not uploaded
                // }

                if ($request->hasFile('foto')) {
                    $foto = $request->file('foto');

                    // Generate a unique file name
                    $uniqueFotoName = time() . '_' . $foto->getClientOriginalName();

                    // Store the file and save the path in the investorDetail object
                    $investorDetail->foto = $foto->storeAs('foto', $uniqueFotoName, 'public');
                } else {
                    // Keep existing photo if not uploaded
                    $investorDetail->foto = $user->investorDetails->foto;
                }

                $investorDetail->save(); // Save the updated investor detail with the photo

                // Update or create personal or company details based on the selected category
                if ($request->input('category') === 'personal') {
                    $user->personalDetails()->updateOrCreate(
                        ['investor_details_id' => $investorDetail->id],
                        $request->only([
                            'npwp_number_inves_personal',
                            'job',
                            'total_assets',
                            'profit_inves_personal',
                        ])
                    );
                } elseif ($request->input('category') === 'perusahaan') {
                    $user->perusahaanDetails()->updateOrCreate(
                        ['investor_details_id' => $investorDetail->id],
                        $request->only([
                            'institution_name',
                            'establishment_date_inves_perusahaan',
                            'description_inves_perusahaan',
                            'npwp_number_inves_perusahaan',
                            'siup_number_inves_perusahaan',
                            'nib_number',
                            'profit_inves_perusahaan',
                        ])
                    );
                }
                break;

            case 'akademisi':
                // Prepare the data to update or create
                $dataToUpdate = $request->only([
                    'university_name',
                    'description_akademisi',
                    'faculty',
                    'study_program',
                    'expertise_field',
                ]);

                // // Handle the file upload if there is a file
                // if ($request->hasFile('foto')) {
                //     $dataToUpdate['foto'] = $request->file('foto')->storeAs(
                //         'foto',
                //         $request->file('foto')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $dataToUpdate['foto'] = $user->akademisiDetails->foto; // Keep existing photo if not uploaded
                // }

                // Handle the file upload if there is a file
                if ($request->hasFile('foto')) {
                    $foto = $request->file('foto');

                    // Generate a unique file name
                    $uniqueFotoName = time() . '_' . $foto->getClientOriginalName();

                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['foto'] = $foto->storeAs('foto', $uniqueFotoName, 'public');
                } else {
                    // Keep existing photo if not uploaded
                    $dataToUpdate['foto'] = $user->akademisiDetails->foto;
                }


                // Update or create the akademisi details
                $user->akademisiDetails()->updateOrCreate(
                    ['user_id' => $user->id],
                    $dataToUpdate
                );
                break;

            case 'komunitas':
                // Prepare the data to update or create
                $dataToUpdate = $request->only([
                    'community_name',
                    'establishment_date_komunitas',
                    'description_komunitas',
                    'community_license',
                ]);

                // Handle the file upload if there is a file
                // if ($request->hasFile('foto')) {
                //     $dataToUpdate['foto'] = $request->file('foto')->storeAs(
                //         'foto',
                //         $request->file('foto')->getClientOriginalName(),
                //         'public'
                //     );
                // } else {
                //     $dataToUpdate['foto'] = $user->komunitasDetails->foto; // Keep existing photo if not uploaded
                // }


                if ($request->hasFile('foto')) {
                    $foto = $request->file('foto');
                    
                    // Generate a unique file name
                    $uniqueFotoName = time() . '_' . $foto->getClientOriginalName();
                    
                    // Store the file and save the path in the dataToUpdate array
                    $dataToUpdate['foto'] = $foto->storeAs('foto', $uniqueFotoName, 'public');
                } else {
                    // Keep existing photo if not uploaded
                    $dataToUpdate['foto'] = $user->komunitasDetails->foto; 
                }
                
                // Update or create the komunitas details
                $user->komunitasDetails()->updateOrCreate(
                    ['user_id' => $user->id],
                    $dataToUpdate
                );
                break;

            default:
                return response()->json(['error' => 'Invalid role'], 400);
        }


        // Redirect to the profile page after the update
        return redirect()->route('profile.show')->with('success', 'Profile updated successfully.');
    }
}
