<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function updateAjax(Request $request)
    {
        $siswa = Auth::guard('siswa')->user();

        $request->validate([
            'password'              => 'nullable|min:6|confirmed',
            'password_confirmation' => 'nullable',
            'foto_profil'           => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ], [
            'password.min'       => 'Password minimal 6 karakter.',
            'password.confirmed' => 'Konfirmasi password tidak cocok.',
            'foto_profil.image'  => 'File harus berupa gambar.',
            'foto_profil.max'    => 'Ukuran foto maksimal 2MB.',
        ]);

        $data    = [];
        $fotoUrl = null;

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

        if ($request->hasFile('foto_profil')) {
            if ($siswa->foto_profil && Storage::disk('public')->exists($siswa->foto_profil)) {
                Storage::disk('public')->delete($siswa->foto_profil);
            }
            $path = $request->file('foto_profil')->store('foto_profil/siswa', 'public');
            $data['foto_profil'] = $path;
            $fotoUrl = Storage::url($path);
        }

        if (!empty($data)) {
            $siswa->update($data);
        }

        return response()->json([
            'success'  => true,
            'message'  => 'Profil berhasil diperbarui!',
            'foto_url' => $fotoUrl ?? ($siswa->foto_profil ? Storage::url($siswa->foto_profil) : null),
        ]);
    }
}