<?php

namespace App\Http\Controllers;

use App\Models\Mahasiswa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Validator;
use Illuminate\Support\Facades\DB;

class MahasiswaController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['only' => ['store', 'update', 'destroy', 'index', 'show']]);
    }

    public function index(Request $request)
    {
        $mahasiswa = Mahasiswa::all();

        return response()->json($mahasiswa);
    }
    
    public function show($id)
    {
        // Menggunakan eager loading untuk memuat relasi yang diperlukan
        $mahasiswa = Mahasiswa::with(['tahun_ajar', 'semester', 'jurusan','agama', 'kelurahan', 'kecamatan', 'kabupaten',  'provinsi'])
            ->where('nim', $id)
            ->first();
    
        if (!$mahasiswa) {
            return response()->json(['message' => 'Data not found'], 404);
        }
        
        return response()->json($mahasiswa);
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), Mahasiswa::dataInputRules());
    
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], 422);
        }
    
        $dataInput = $request->only(Mahasiswa::dataInput());
    
        $mahasiswa = Mahasiswa::create($dataInput);
    
        return response()->json(['mahasiswa' => $mahasiswa], 201);
    }


    public function update(Request $request, $id)
    {
        // Menggunakan WHERE pada kolom id_modul
        $mahasiswa = Mahasiswa::where('nim', $id)->first();
    
        if (!$mahasiswa) {
            return response()->json(['message' => 'Data not found'], 404);
        }
    
        $validator = Validator::make($request->all(), Mahasiswa::dataUpdateRules($id));

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], 422);
        }
    
        $mahasiswa->update($request->only(Mahasiswa::dataInput()));
    
        // Log pesan debug
        error_log("Update success: " . json_encode($mahasiswa));
    
        return response()->json(['mahasiswa' => $mahasiswa]);
    }

    
    public function destroy($id)
    {
        $mahasiswa = Mahasiswa::where('nim', $id)->first();
    
        if (!$mahasiswa) {
            return response()->json(['message' => 'Data not found'], 404);
        }
    
        $del_mahasiswa = $mahasiswa->replicate();
    
        if ($mahasiswa->delete()) {
            $output = [
                'item_deleted' => $del_mahasiswa,
                'message' => 'Mahasiswa deleted successfully'
            ];
    
            return response()->json($output, 200);
        } else {
            return response()->json(['message' => 'Failed to delete Mahasiswa'], 500);
        }
    }
}
