<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FacultyProfile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class FacultyProfileController extends Controller
{
    /**
     * Show logged-in user's faculty profile.
     */
    public function index()
    {
        $user = Auth::user();
        $profile = FacultyProfile::firstOrCreate(
            ['user_id' => $user->id],
            [
                'name' => $user->name ?? '',
                'email' => $user->email ?? '',
                'phone_number' => '',
                'vidhvan_id' => '',
                'google_scholar_id' => '',
                'linkedin_id' => '',
                'designation' => '',
                'salutation' => '',
                'qualification' => '',
                'address' => '',
                'employee_id' => '',
                'department_name' => '',
                'programme_name' => '',
                'date_of_joining' => now()->toDateString(),
            ]
        );

        return view('profile.index', compact('user', 'profile'));
    }

    /**
     * Show the edit form for faculty profile.
     */
    public function edit()
    {
        $user = Auth::user();
        $profile = FacultyProfile::where('user_id', $user->id)->firstOrFail();

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

    /**
     * Update faculty profile.
     */
    public function update(Request $request)
    {
        $user = Auth::user();
        $profile = FacultyProfile::where('user_id', $user->id)->firstOrFail();

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'phone_number' => 'nullable|string|max:20',
            'employee_id' => 'nullable|string|max:255',
            'department_name' => 'nullable|string|max:255',
            'programme_name' => 'nullable|string|max:255',
            'salutation' => 'nullable|string|max:50',
            'designation' => 'nullable|string|max:255',
            'date_of_joining' => 'nullable|date',
            'qualification' => 'nullable|string|max:500',
            'address' => 'nullable|string|max:500',
            'google_scholar_id' => 'nullable|string|max:255',
            'vidhvan_id' => 'nullable|string|max:255',
            'linkedin_id' => 'nullable|string|max:255',
            'profile_photo' => 'nullable|image|max:2048', // 2MB max
        ]);

        // Handle profile photo upload
        if ($request->hasFile('profile_photo')) {
            if ($profile->profile_photo_path && Storage::exists($profile->profile_photo_path)) {
                Storage::delete($profile->profile_photo_path);
            }

            $validated['profile_photo_path'] = $request->file('profile_photo')
                ->store('public/profile_photos');
        }

        // Update profile with validated data
        $profile->update([
            'name' => $validated['name'] ?? $profile->name,
            'email' => $validated['email'] ?? $profile->email,
            'phone_number' => $validated['phone_number'] ?? '',
            'employee_id' => $validated['employee_id'] ?? '',
            'department_name' => $validated['department_name'] ?? '',
            'programme_name' => $validated['programme_name'] ?? '',
            'salutation' => $validated['salutation'] ?? '',
            'designation' => $validated['designation'] ?? '',
            'date_of_joining' => $validated['date_of_joining'] ?? $profile->date_of_joining,
            'qualification' => $validated['qualification'] ?? '',
            'address' => $validated['address'] ?? '',
            'google_scholar_id' => $validated['google_scholar_id'] ?? '',
            'vidhvan_id' => $validated['vidhvan_id'] ?? '',
            'linkedin_id' => $validated['linkedin_id'] ?? '',
            'profile_photo_path' => $validated['profile_photo_path'] ?? $profile->profile_photo_path,
        ]);

        // ✅ Update the main user record (used by PublicationsController)
        if ($request->filled('google_scholar_id')) {
            $user->scholar_url = $request->input('google_scholar_id');
            $user->save();
        }

        // ✅ Refresh session to ensure it reflects the latest Scholar URL immediately
        Auth::setUser($user->fresh());

        return redirect()
            ->route('faculty.profile.index')
            ->with('success', 'Profile updated successfully.');
    }
}
