<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginMobileController extends Controller
{
    public function login(Request $request)
    {
        $nisn = $request->input('nisn');
        $password = $request->input('password');

        $siswa = DB::table('siswa')
            ->join('kelas', 'siswa.id_kelas', '=', 'kelas.id_kelas')
            ->select('siswa.*', 'kelas.nama_kelas')
            ->where('siswa.nisn', $nisn)
            ->first();

        if (!$siswa) {
            // Jika nisn tidak ditemukan
            $response = array(
                'success' => false,
                'message' => 'NISN tidak ditemukan',
            );
        } else if ($password != $siswa->password) {
            // Jika nisn cocok tetapi password salah
            $response = array(
                'success' => false,
                'message' => 'Password salah',
            );
        } else {
            // Jika nisn dan password cocok
            $response = array(
                'success' => true,
                'message' => 'Login Berhasil',
                'siswa' => array(
                    'nisn' => $siswa->nisn,
                    'nama_siswa' => $siswa->nama_siswa,
                    'tempat_lahir' => $siswa->tempat_lahir,
                    'tanggal_lahir' => $siswa->tanggal_lahir,
                    'password' => $siswa->password,
                    'nomor_hp' => $siswa->nomor_hp,
                    'id_kelas' => $siswa->id_kelas,
                    'nama_kelas' => $siswa->nama_kelas, // Menambahkan nama_kelas
                    'alamat' => $siswa->alamat,
                ),
            );
        }

        return response()->json($response);
    }


    public function loginGuru (Request $request){
        $nip = $request->input('nip');
        $password = $request->input('password');

        $guru = DB::table('guru')
            ->select('guru.*')
            ->where('guru.nip', $nip)
            ->first();

        if (!$guru) {
            // Jika nisn tidak ditemukan
            $response = array(
                'success' => false,
                'message' => 'NIP tidak ditemukan',
            );
        } else if ($password != $guru->password) {
            // Jika nisn cocok tetapi password salah
            $response = array(
                'success' => false,
                'message' => 'Password salah',
            );
        } else {
            // Jika nisn dan password cocok
            $response = array(
                'success' => true,
                'message' => 'Login Berhasil',
                'guru' => array(
                    'nip' => $guru->nip,
                    'nama_guru' => $guru->nama_guru,
                    'password' => $guru->password,
                    'nomor_hp' => $guru->nomor_hp
                ),
            );
        }

        return response()->json($response);
    }
}
