<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Siswa\BaseController;

class PasswordController extends BaseController
{
    public function edit()
    {
        $response = Http::withToken(session('token'))
            ->get(config('services.lms.api') . '/siswa/profile');

        if ($redirect = $this->handleApi($response)) {
            return $redirect;
        }
        
        if ($response->failed()) {
            return redirect()
                ->route('siswa.dashboard')
                ->with('error','Gagal mengambil data siswa');
        }

        $student = json_decode(json_encode(
            $response->json('data.student')
        ));

        return view('siswa.profile.password', compact('student'));
    }


    public function update(Request $request)
    {
        $response = Http::withToken(session('token'))
            ->post(
                config('services.lms.api') . '/siswa/password',
                $request->only([
                    'current_password',
                    'password',
                    'password_confirmation',
                ])
            );

        // 🔐 TOKEN EXPIRED
        if ($redirect = $this->handleApi($response)) {
            return $redirect;
        }

        // ❌ VALIDATION ERROR
        if ($response->status() === 422) {
            return back()->withErrors(
                $response->json('errors')
            )->withInput();
        }

        if ($response->failed()) {
            return redirect()
                ->route('siswa.dashboard')
                ->with('error','Gagal memperbarui password');
        }

        // ✅ SUCCESS → PAKSA LOGIN ULANG
        session()->forget(['token', 'role']);

        return redirect()
            ->to(config('services.login.url'))
            ->with('status', $response->json('message'));
    }
}
