<?php

namespace App\Http\Controllers;

use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class SettingsController extends Controller
{
    /**
     * Show the index settings page.
     */
    public function index(): View
    {
        $user = auth()->user();
        $activeJob = $user->jobExperiences()->where('still_employed', true)->first();

        return view('dashboard.settings.index', compact('user', 'activeJob'));
    }

    public function update(Request $request)
    {
        $user = auth()->user();

        $rules = [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'user_name' => 'required|string|unique:users,user_name,' . $user->id,
            'email' => 'required|email|unique:users,email,' . $user->id,
            // Job-related fields
            'job_title' => 'nullable|string|max:255',
            'company' => 'nullable|string|max:255',
            'location' => 'nullable|string|max:255',
            // Privacy
            'profile_visibility' => 'required|in:public,private,connections',
            'display_name_format' => 'required|in:full_name,first_name,username',
            'show_ratings' => ['boolean'],
            'show_experience' => ['boolean'],
            'allow_messages' => ['boolean'],
            'email_notifications' => ['boolean'],
        ];
        

        // Add password rules ONLY if a new password is typed
        if ($request->filled('password')) {
            $rules['current_password'] = ['required', 'current_password'];
            $rules['password'] = ['required', 'confirmed', 'min:5'];
        }

        // Run validation ONCE
        $validated = $request->validate($rules);
        

        DB::transaction(function () use ($user, $request, $validated) {
            // Update User Table
            $userData = [
                'name' => $validated['first_name'] . ' ' . $validated['last_name'],
                'user_name' => $validated['user_name'],
                'email' => $validated['email'],
                'profile_visibility' => $validated['profile_visibility'],
                'display_name_format' => $validated['display_name_format'],
                
                // Notification/Privacy Toggles (Checkbox Logic)
                'include_in_stats' => $request->boolean('include_in_stats'),
                'show_salary_to_connections' => $request->boolean('show_salary_to_connections'),
                'allow_comparison_requests' => $request->boolean('allow_comparison_requests'),
                'show_activity_to_connections' => $request->boolean('show_activity_to_connections'),
                'show_online_status' => $request->boolean('show_online_status'),
                'product_updates' => $request->boolean('product_updates'),
                'weekly_reports' => $request->boolean('weekly_reports'),
                'marketing_emails' => $request->boolean('marketing_emails'),
                'notify_messages' => $request->boolean('notify_messages'),
                'notify_connections' => $request->boolean('notify_connections'),
                'notify_activity' => $request->boolean('notify_activity'),
                'push_messages' => $request->boolean('push_messages'),
                'push_alerts' => $request->boolean('push_alerts'),
                'show_ratings' => $request->boolean('show_ratings'),
                'show_experience' => $request->boolean('show_experience'),
                'allow_messages' => $request->boolean('allow_messages'),
                'email_notifications' => $request->boolean('email_notifications'),
            ];

            // Update password if provided
            if ($request->filled('password')) {
                $userData['password'] = Hash::make($request->password);
            }

            $user->update($userData);

            // Update Active Job Experience
            // We look for the job currently marked as 'still_employed'
            $activeJob = $user->jobExperiences()->where('still_employed', true)->first();

            if ($activeJob) {
                $activeJob->update([
                    'job_title' => $request->input('job_title'),
                    'company_name' => $request->input('company'),
                    'location' => $request->input('location'),
                ]);
            }
        });

        return back()->with('status', 'settings-updated');
    }
}
