<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\PenawaranProject;
use App\Models\permohonanProject;
use App\Models\Preference;
use App\Models\Preferences;
use App\Models\PreferencesPermohonan;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    /**
     * Display the user's profile form.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $request->user()->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }

    public function show(Request $request)
    {
        $user = Auth::user();
        $detail = null;
        $filters = $request->all(); // Get all the request input data for filtering projects

        $userFilters = Preference::where('user_id', $user->id)->first();
        $selectedFilters = [];

        if ($userFilters) {
            $selectedFilters = json_decode($userFilters->filters, true) ?? []; // Menggunakan true untuk mengembalikan array
        }


        // Retrieve preferences for the logged-in user
        $preferences = Preference::where('user_id', $user->id)->first();

        switch ($user->role) {
            case 'pemerintah':
                $detail = $user->pemerintahDetails;

                break;
            case 'umkm':
                $detail = $user->umkmDetails;
                break;
            case 'investor':
                $detail = $user->investorDetails; // Get the investor details
                $foto = null; // Initialize foto variable

                if ($detail->category === 'personal') {
                    $personalDetail = $detail->personalDetails; // Get personal details
                    $foto = $detail->foto; // Get foto from investorDetails, or replace with $personalDetail->foto if applicable
                } elseif ($detail->category === 'perusahaan') {
                    $perusahaanDetail = $detail->perusahaanDetails; // Get company details
                    $foto = $detail->foto; // Get foto from investorDetails, or replace with $perusahaanDetail->foto if applicable
                }
                break;

            case 'akademisi':
                $detail = $user->akademisiDetails;
                break;
            case 'komunitas':
                $detail = $user->komunitasDetails;
                break;
        }

        return view('profile.show', compact('user', 'detail', 'preferences', 'selectedFilters'));
    }

    public function detail($id)
    {
        // Retrieve the user by the given ID
        $user = User::with(['pemerintahDetails', 'umkmDetails', 'investorDetails', 'akademisiDetails', 'komunitasDetails'])
            ->findOrFail($id); // Fetch user by ID

        // Initialize the detail variable
        $detail = null;

        // Get user details based on the user's role
        switch ($user->role) {
            case 'pemerintah':
                $detail = $user->pemerintahDetails;
                break;
            case 'umkm':
                $detail = $user->umkmDetails;
                break;
            case 'investor':
                $detail = $user->investorDetails; // Get the investor details
                $foto = null; // Initialize foto variable

                if ($detail->category === 'personal') {
                    $personalDetail = $detail->personalDetails; // Get personal details
                    $foto = $detail->foto; // Get foto from investorDetails
                } elseif ($detail->category === 'perusahaan') {
                    $perusahaanDetail = $detail->perusahaanDetails; // Get company details
                    $foto = $detail->foto; // Get foto from investorDetails
                }
                break;
            case 'akademisi':
                $detail = $user->akademisiDetails;
                break;
            case 'komunitas':
                $detail = $user->komunitasDetails;
                break;
        }

        // Return the profile detail view with the fetched user and details
        return view('profile.detail', compact('user', 'detail'));
    }

    public function storePreferencesPermohonan(Request $request)
    {

        $user = Auth::user();

        // Validasi input
        $request->validate([
            'bidang_sub_sektor_ekonomi_kreatif' => 'array',
            'kategori' => 'array',
            'batas_terima_tawaran' => 'date|nullable',
            'range_min' => 'numeric|nullable',
            'range_max' => 'numeric|nullable',
            'status' => 'array',
        ]);

        // Ambil atau buat preferences
        $preferences = PreferencesPermohonan::updateOrCreate(
            ['user_id' => $user->id], // Kondisi untuk mencari record
            [
                'bidang_sub_sektor_ekonomi_kreatif' => json_encode($request->bidang_sub_sektor_ekonomi_kreatif),
                'kategori' => json_encode($request->kategori),
                'batas_terima_tawaran' => $request->batas_terima_tawaran,
                'range_min' => $request->range_min,
                'range_max' => $request->range_max,
                'status' => json_encode($request->status),
            ]
        );

        return redirect()->back()->with('success', 'Preferences updated successfully.');
    }
}
