<?php

namespace App\Http\Controllers;

use App\Models\AkunTeknisi;
use App\Models\Teknisi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AkunTeknisiController extends Controller
{
    /**
     * Tampilkan daftar semua akun teknisi.
     */
    public function index()
    {
        $akunTeknisis = AkunTeknisi::with('teknisi')->get();
        $teknisis = Teknisi::whereNotIn('id_teknisi', 
            AkunTeknisi::pluck('id_teknisi'))->get();
        
        return view('Admin.KelolaTeknisi.AkunTeknisi', compact('akunTeknisis', 'teknisis'));
    }

    /**
     * Tampilkan form untuk membuat akun teknisi baru.
     */
    public function create()
    {
        $teknisi = Teknisi::all();
        return view('Admin.KelolaTeknisi.create-akun', compact('teknisi'));
    }

    /**
     * Simpan akun teknisi baru ke database.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_teknisi' => 'required|exists:teknisis,id_teknisi|unique:akun_teknisis,id_teknisi',
            'username' => 'required|string|max:255|unique:akun_teknisis,username',
            'password' => 'required|string|min:6',
            'status' => 'required|in:aktif,tidak_aktif',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            AkunTeknisi::create([
                'id_teknisi' => $request->id_teknisi,
                'username' => $request->username,
                'password' => Hash::make($request->password),
                'password_plain' => $request->password,
                'status' => $request->status,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Akun teknisi berhasil dibuat!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal membuat akun teknisi: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Tampilkan detail akun teknisi tertentu.
     */
    public function show($id)
    {
        try {
            $akunTeknisi = AkunTeknisi::with('teknisi')->findOrFail($id);
            return response()->json($akunTeknisi);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Akun teknisi tidak ditemukan'
            ], 404);
        }
    }

    /**
     * Tampilkan form untuk mengedit akun teknisi.
     */
    public function edit($id)
    {
        try {
            $akunTeknisi = AkunTeknisi::with('teknisi')->findOrFail($id);
            return response()->json($akunTeknisi);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Akun teknisi tidak ditemukan'
            ], 404);
        }
    }

    /**
     * Update akun teknisi di database.
     */
    public function update(Request $request, $id)
    {
        try {
            $akunTeknisi = AkunTeknisi::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'id_teknisi' => 'required|exists:teknisis,id_teknisi|unique:akun_teknisis,id_teknisi,' . $id . ',id_akun_teknisi',
                'username' => 'required|string|max:255|unique:akun_teknisis,username,' . $id . ',id_akun_teknisi',
                'password' => 'nullable|string|min:6',
                'status' => 'required|in:aktif,tidak_aktif',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $updateData = [
                'id_teknisi' => $request->id_teknisi,
                'username' => $request->username,
                'status' => $request->status,
            ];

            // Hanya update password jika diisi
            if ($request->filled('password')) {
                $updateData['password'] = Hash::make($request->password);
                $updateData['password_plain'] = $request->password;
            }

            $akunTeknisi->update($updateData);

            return response()->json([
                'success' => true,
                'message' => 'Akun teknisi berhasil diupdate!'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal update akun teknisi: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Hapus akun teknisi dari database.
     */
    public function destroy($id)
    {
        try {
            $akunTeknisi = AkunTeknisi::findOrFail($id);
            $akunTeknisi->delete();

            return response()->json([
                'success' => true,
                'message' => 'Akun teknisi berhasil dihapus!'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal hapus akun teknisi: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Login untuk teknisi (Mobile App).
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            // Cari akun teknisi
            $akun = AkunTeknisi::where('username', $request->username)
                ->where('status', 'aktif')
                ->with('teknisi')
                ->first();

            // Cek kredensial
            if (!$akun || !Hash::check($request->password, $akun->password)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Username atau password salah'
                ], 401);
            }

            // Generate JWT token
            $token = auth('api')->login($akun);

            if (!$token) {
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal membuat token'
                ], 500);
            }

            return response()->json([
                'success' => true,
                'message' => 'Login berhasil',
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth('api')->factory()->getTTL() * 60,
                'user' => [
                    'id_akun_teknisi' => $akun->id_akun_teknisi,
                    'username' => $akun->username,
                    'status' => $akun->status,
                    'teknisi' => $akun->teknisi
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat login: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Logout teknisi.
     */
    public function logout()
    {
        try {
            auth('api')->logout();

            return response()->json([
                'success' => true,
                'message' => 'Logout berhasil'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat logout: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get profile teknisi yang sedang login.
     */
    public function me()
    {
        try {
            $akun = auth('api')->user();
            
            if (!$akun) {
                return response()->json([
                    'success' => false,
                    'message' => 'User tidak ditemukan'
                ], 404);
            }

            // Load relasi teknisi
            $akun->load('teknisi');

            return response()->json([
                'success' => true,
                'message' => 'Data berhasil diambil',
                'data' => [
                    'id_akun_teknisi' => $akun->id_akun_teknisi,
                    'username' => $akun->username,
                    'status' => $akun->status,
                    'teknisi' => $akun->teknisi
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Refresh JWT token.
     */
    public function refresh()
    {
        try {
            $newToken = auth('api')->refresh();

            return response()->json([
                'success' => true,
                'message' => 'Token berhasil di-refresh',
                'access_token' => $newToken,
                'token_type' => 'bearer',
                'expires_in' => auth('api')->factory()->getTTL() * 60
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal refresh token: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Change password teknisi.
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'password_lama' => 'required|string',
            'password_baru' => 'required|string|min:6|confirmed',
        ], [
            'password_baru.confirmed' => 'Konfirmasi password tidak sesuai',
            'password_baru.min' => 'Password baru minimal 6 karakter',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validasi gagal',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $akun = auth('api')->user();

            // Cek password lama
            if (!Hash::check($request->password_lama, $akun->password)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Password lama tidak sesuai'
                ], 401);
            }

            // Update password
            $akun->update([
                'password' => Hash::make($request->password_baru)
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Password berhasil diubah'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengubah password: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update status akun teknisi.
     */
    public function updateStatus(Request $request, $id)
    {
        try {
            $akunTeknisi = AkunTeknisi::findOrFail($id);
            
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:aktif,tidak_aktif',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $akunTeknisi->update([
                'status' => $request->status
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Status akun teknisi berhasil diupdate!'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal update status: ' . $e->getMessage()
            ], 500);
        }
    }
}