<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Mahasiswa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use Illuminate\Support\Facades\Validator;


class UserController extends Controller
{
    public function index()
    {
        $users = User::select('id', 'name', 'email', 'role', 'created_at')
        ->with(['mahasiswa' => function($query) {
            $query->select('user_id', 'nim', 'program_studi');
        }])
        ->orderBy('created_at', 'desc')
        ->paginate(20); // Reduced from 20 to 10-15 if possible
        
    return view('admin.user.index', compact('users'));
    }

    // public function create(Request $request)
    // {
    //     $defaultRole = $request->has('force_mahasiswa') ? 'mahasiswa' : 'mahasiswa';
        
    //     return view('admin.user.create', [
    //         'defaultRole' => $defaultRole,
    //         'force_mahasiswa' => $request->has('force_mahasiswa')
    //     ]);
    // }

    public function store(StoreUserRequest $request)
    {
        $role = $request->has('force_mahasiswa') ? 'mahasiswa' : $request->role;
    
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $role,
            'alamat' => $request->alamat ?? 'Belum diisi',
            'telepon' => $request->telepon ?? 'Belum diisi',
            'keterangan' => $role === 'mahasiswa' ? 'Mahasiswa' : $request->keterangan
        ]);
        
        if ($role === 'mahasiswa') {
            Mahasiswa::create([
                'user_id' => $user->id,
                'nim' => $request->nim,
                'program_studi' => $request->program_studi,
                'jurusan' => $request->jurusan,
                'no_hp' => $request->no_hp
            ]);
        }
    
        if ($request->has('force_mahasiswa')) {
            return redirect()->route('login')->with('success', 'Registrasi berhasil! Silakan login.');
        }
        
        return redirect()->route('user.index')->with('success', 'User berhasil dibuat');
    }

    public function update(UpdateUserRequest $request, $id)
    {
    $user = User::with('mahasiswa')->findOrFail($id);

    DB::transaction(function () use ($request, $user) {
        $previousRole = $user->role;
        
        $user->update([
            'name' => $request->name,
            'email' => $request->email,
            'alamat' => $request->alamat,
            'telepon' => $request->telepon,
            'keterangan' => $request->keterangan,
            'role' => $request->role
        ]);

        // Handle perubahan role
        if ($previousRole !== $request->role) {
            if ($request->role === 'mahasiswa') {
                $request->validate([
                    'nim' => 'required|unique:mahasiswas,nim,'.$user->id.',user_id',
                    'program_studi' => 'required|string',
                    'jurusan' => 'required|string',
                    'no_hp' => 'required'
                ]);

                // Buat atau update data mahasiswa
                $mahasiswaData = [
                    'nim' => $request->nim,
                    'program_studi' => $request->program_studi,
                    'jurusan' => $request->jurusan,
                    'no_hp' => $request->no_hp
                ];

                if ($user->mahasiswa) {
                    $user->mahasiswa()->update($mahasiswaData);
                } else {
                    $user->mahasiswa()->create($mahasiswaData);
                }
            } else {
                if ($user->mahasiswa) {
                    $user->mahasiswa()->delete();
                }
            }
        } else {
            if ($request->role === 'mahasiswa') {
                $request->validate([
                    'nim' => 'required|unique:mahasiswas,nim,'.$user->id.',user_id',
                    'program_studi' => 'required|string',
                    'jurusan' => 'required|string',
                    'no_hp' => 'required'
                ]);

                $user->mahasiswa()->updateOrCreate(
                    ['user_id' => $user->id],
                    [
                        'nim' => $request->nim,
                        'program_studi' => $request->program_studi,
                        'jurusan' => $request->jurusan,
                        'no_hp' => $request->no_hp
                    ]
                );
            }
        }
    });

    return redirect()->route('user.index')->with('success', 'User berhasil diperbarui');
    }

    public function destroy($id)
    {
    try {
        DB::transaction(function () use ($id) {
            $user = User::with('mahasiswa')->findOrFail($id);
            
            if ($user->mahasiswa) {
                $user->mahasiswa()->delete();
            }
            
            $user->delete();
        });

        return redirect()->route('user.index')
            ->with('success', 'User berhasil dihapus');

    } catch (\Exception $e) {
        return redirect()->back()
            ->with('error', 'Gagal menghapus user: '.$e->getMessage());
    }
    }

    protected function createMahasiswaData(User $user, Request $request)
    {
        $request->validate([
            'nim' => 'required|unique:mahasiswas,nim',
            'program_studi' => 'required|string',
            'jurusan' => 'required|string',
            'no_hp' => 'required'
        ]);

        return $user->mahasiswa()->create([
            'nim' => $request->nim,
            'program_studi' => $request->program_studi,
            'jurusan' => $request->jurusan,
            'no_hp' => $request->no_hp
        ]);
    }

    protected function handleMahasiswaData(User $user, Request $request)
    {
        if ($request->role === 'mahasiswa') {
            $mahasiswaData = $request->only('nim', 'program_studi', 'jurusan', 'no_hp');
            
            if ($user->mahasiswa) {
                $user->mahasiswa()->update($mahasiswaData);
            } else {
                $this->createMahasiswaData($user, $request);
            }
        } else {
            if ($user->mahasiswa) {
                $user->mahasiswa()->delete();
            }
        }
    }

    public function completeData($id)
    {
    $user = User::with('mahasiswa')->findOrFail($id);
    
    if ($user->role === 'mahasiswa' && !$user->mahasiswa) {
        return view('admin.user.complete-mahasiswa', compact('user'));
    }

    return redirect()->back()->with('error', 'User tidak memerlukan pelengkapan data');
    }

    public function storeCompleteData(Request $request, $id)
    {
    $user = User::findOrFail($id);
    
    $request->validate([
        'nim' => 'required|unique:mahasiswas,nim',
        'program_studi' => 'required|string',
        'jurusan' => 'required|string',
        'no_hp' => 'required'
    ]);

    $user->mahasiswa()->create([
        'nim' => $request->nim,
        'program_studi' => $request->program_studi,
        'jurusan' => $request->jurusan,
        'no_hp' => $request->no_hp
    ]);

    return redirect()->route('user.index')->with('success', 'Data mahasiswa berhasil dilengkapi');
    }

    public function showMahasiswaRegistrationForm()
    {   
        return view('auth.register-mahasiswa', [
            'hideAdminFields' => true
        ]);
    }

    public function registerMahasiswa(Request $request)
{
    try {
        // Custom validation rules
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'string',
                'regex:/^[A-Za-z\s]+$/',
                'max:255',
                function ($attribute, $value, $fail) {
                    if (preg_match('/[0-9]/', $value)) {
                        $fail('Nama tidak boleh mengandung angka.');
                    }
                },
            ],

            'email' => [
                'required',
                'email',
                'max:255',
                'unique:users',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/@student\.polije\.ac\.id$/', $value)) {
                        $fail('Hanya email @student.polije.ac.id yang diperbolehkan.');
                    }
                },
            ],
            'password' => 'required|string|min:8|confirmed',
            'nim' => [
                'required',
                'string',
                'size:9',
                'unique:mahasiswas',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^[A-Z][0-9]{8}$/', $value)) {
                        $fail('Format NIM tidak valid. Harus diawali huruf kapital diikuti 8 angka (contoh: E12345678).');
                    }
                },
            ],
            'program_studi' => 'required|string',
            'jurusan' => 'required|string',
            'no_hp' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^[0-9]+$/', $value)) {
                        $fail('Nomor HP hanya boleh mengandung angka.');
                    }
                },
            ],
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'alert_type' => 'error',
                    'alert_message' => 'Terdapat kesalahan dalam pengisian form. Silakan periksa kembali data Anda.'
                ]);
        }

        DB::transaction(function () use ($request) {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'mahasiswa',
                'alamat' => $request->alamat ?? 'Belum diisi',
                'telepon' => $request->telepon ?? 'Belum diisi',
                'keterangan' => 'Mahasiswa'
            ]);

            Mahasiswa::create([
                'user_id' => $user->id,
                'nim' => $request->nim,
                'program_studi' => $request->program_studi,
                'jurusan' => $request->jurusan,
                'no_hp' => $request->no_hp
            ]);
        });

       return redirect()->route('login')
            ->with('register_status', 'success')
            ->with('register_message', 'Registrasi berhasil! Silakan login dengan email dan password Anda');

    } catch (\Exception $e) {
        return back()->withInput()
            ->with('register_status', 'error')
            ->with('register_message', 'Registrasi gagal: ' . $e->getMessage());
    }
}

    public function updateProfile(Request $request)
    {
        Auth::user()->update($request->only('alamat'));

        return response()->json(['message' => 'Profile updated successfully']);
    }
}