<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    // --- FITUR PETANI ---
    public function editPetani()
    {
        $user = Auth::guard('petani')->user();
        return view('petani.profile', compact('user'));
    }

    public function updatePetani(Request $request)
    {
        $user = Auth::guard('petani')->user();

        $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:petanis,email,' . $user->id,
            'password' => 'nullable|min:6|confirmed', 
            'foto' => 'nullable|image|max:2048'
        ]);

        $user->nama_lengkap = $request->nama_lengkap;
        $user->email = $request->email;

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        if ($request->hasFile('foto')) {
            if ($user->foto && Storage::exists('public/' . $user->foto)) {
                Storage::delete('public/' . $user->foto);
            }
            $path = $request->file('foto')->store('avatars', 'public');
            $user->foto = $path; 
        }

        $user->save();
        return back()->with('success', 'Profil berhasil diperbarui!');
    }

    // --- FITUR PEMBELI ---
    public function editPembeli()
    {
        $user = Auth::guard('pembeli')->user();
        return view('landing.profile', compact('user'));
    }

    public function updatePembeli(Request $request)
    {
        $user = Auth::guard('pembeli')->user();

        $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:pembelis,email,' . $user->id,
            'no_hp' => 'required|string',
            'alamat' => 'required|string',
            'password' => 'nullable|min:6|confirmed',
            'foto' => 'nullable|image|max:2048'
        ]);

        $user->nama_lengkap = $request->nama_lengkap;
        $user->email = $request->email;
        $user->no_hp = $request->no_hp;
        $user->alamat = $request->alamat;

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        if ($request->hasFile('foto')) {
            if ($user->foto && Storage::exists('public/' . $user->foto)) {
                Storage::delete('public/' . $user->foto);
            }
            $path = $request->file('foto')->store('avatars', 'public');
            $user->foto = $path;
        }

        $user->save();
        return back()->with('success', 'Profil berhasil diperbarui!');
    }
}
