<?php

// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;

use App\Models\Student;
use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    // POST /login
    public function login(Request $request)
    {
        try {
            $request->validate([
                'username' => 'required|string',
                'password' => 'required|string',
            ]);

            $user = User::where('username', $request->username)->first();
            if (!$user) {
                return response()->json(['error' => 'Invalid username or password'], 401);
            }

            // Express uses MD5 — mirror that for compatibility
            if (md5($request->password) !== $user->password) {
                return response()->json(['error' => 'Invalid username or password'], 401);
            }

            $token = $user->createToken('mobile')->plainTextToken;

            return response()->json([
                'token'      => $token,
                'schoolCode' => $user->username,
                'userInfo'   => [
                    'username' => $user->username,
                    'name'     => $user->name,
                ],
            ]);
        }catch (\Throwable $e) {
            // 👇 Catch and return DB error
            return response()->json([
                'error'   => 'Database error',
                'message' => $e->getMessage(),
            ], 500);
        }

    }

    // POST /reset-password (protected)
    public function resetPassword(Request $request)
    {
        $request->validate([
            'username'        => 'required|string',
            'currentPassword' => 'required|string',
            'newPassword'     => 'required|string|min:4',
        ]);

        $user = User::where('username', $request->username)->first();
        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        if (md5($request->currentPassword) !== $user->password) {
            return response()->json(['error' => 'Current password is incorrect'], 401);
        }

        $user->password = md5($request->newPassword);
        $user->save();

        return response()->json(['message' => 'Password reset successful']);
    }

    // POST /logout (protected)
    public function logout(Request $request)
    {
        try {
            if ($request->user() && $request->user()->currentAccessToken()) {
                $request->user()->currentAccessToken()->delete();
                return response()->json(['message' => 'Logged out successfully']);
            }
            return response()->json(['message' => 'No active token found'], 401);
        } catch (\Throwable $e) {
            return response()->json([
                'error'   => 'Logout failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

}

