<?php

namespace App\Http\Controllers;

use App\Models\FreelancerProfile;
use App\Models\PortfolioItem;
use App\Models\Skill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FreelancerProfileController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $profile = $user->freelancerProfile ?? new FreelancerProfile();
        $skills = Skill::all();
        $userSkills = $user->skills->pluck('id')->toArray();
        $portfolios = $user->portfolioItems;

        return view('freelancer.profile', compact('user', 'profile', 'skills', 'userSkills', 'portfolios'));
    }

    public function updateBio(Request $request)
    {
        $request->validate([
            'title' => 'nullable|string|max:255',
            'location' => 'nullable|string|max:255',
            'hourly_rate' => 'nullable|numeric|min:0',
            'availability' => 'required|in:available,unavailable',
            'bio' => 'nullable|string',
        ]);

        $user = auth()->user();
        $profile = $user->freelancerProfile ?? new FreelancerProfile(['user_id' => $user->id]);
        
        $profile->fill($request->all());
        $profile->save();

        return back()->with('success', 'Bio and basic details updated.');
    }

    public function updateSkills(Request $request)
    {
        $request->validate([
            'skills' => 'nullable|array',
            'skills.*' => 'exists:skills,id',
        ]);

        auth()->user()->skills()->sync($request->skills ?? []);

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

    public function updateExperience(Request $request)
    {
        $request->validate([
            'education' => 'nullable|string',
            'experience' => 'nullable|string',
        ]);

        $user = auth()->user();
        $profile = $user->freelancerProfile ?? new FreelancerProfile(['user_id' => $user->id]);
        
        $profile->education = $request->education;
        $profile->experience = $request->experience;
        $profile->save();

        return back()->with('success', 'Education and Experience updated.');
    }

    public function addPortfolio(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'url' => 'nullable|url',
        ]);

        $data = $request->except('image');

        // add a simple image handling inside public/portfolios if there is image later.
        // Wait, schema specifies `url`, `title`, `description`. 
        // Migration does NOT have `image` column for portfolio items.
        // The instructions say "image upload", so I will upload an image but the DB schema `portfolio_items` is missing `image`. 
        // Wait, the prompt module 5 says: "Portfolio items (title, image upload, link)".
        // I will just add image column via migration if missing, or use URL for now. 
        // Let's rely on what we have (url/description) to prevent another migration failure, or save image path to url.
        // I'll save image path to url if not a valid HTTP URL.
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('portfolios', 'public');
            $data['url'] = $path;
        }

        $data['user_id'] = auth()->id();
        PortfolioItem::create($data);

        return back()->with('success', 'Portfolio item added.');
    }

    public function deletePortfolio($id)
    {
        $item = PortfolioItem::where('user_id', auth()->id())->findOrFail($id);
        if ($item->url && !str_starts_with($item->url, 'http')) {
            if (Storage::disk('public')->exists($item->url)) {
                Storage::disk('public')->delete($item->url);
            }
        }
        $item->delete();

        return back()->with('success', 'Portfolio item removed.');
    }

    public function show($id)
    {
        $user = \App\Models\User::with(['freelancerProfile', 'skills', 'portfolioItems'])->findOrFail($id);
        
        if ($user->user_type !== 'freelancer') {
            abort(404);
        }

        $profile = $user->freelancerProfile;

        return view('freelancer.public-profile', compact('user', 'profile'));
    }
}
