<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException; 

class AdminUserController extends Controller
{
    /**
     * Menampilkan daftar semua user/karyawan beserta Hak Aksesnya
     */
    public function index(Request $request)
    {
        try {
            $authUser = $request->user();
            
            $query = User::with(['branch', 'permissions']);
            
            if ($authUser && $authUser->role !== 'owner') {
                $query->where('branch_id', $authUser->branch_id);
            }

            if ($request->has('role')) {
                $query->where('role', $request->role);
            }

            $users = $query->orderBy('name', 'asc')->get();

            return response()->json([
                'success' => true,
                'data' => $users
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data user: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Menyimpan user baru & Hak Akses
     */
    public function store(Request $request)
    {
        $authUser = $request->user();

        // PERBAIKAN: Ganti email dengan username
        $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|unique:users,username', 
            'password' => 'required|min:6',
            'role' => 'required|string',
        ]);

        if ($authUser && $authUser->role !== 'owner') {
            if (strtolower($request->role) === 'owner') {
                return response()->json([
                    'success' => false, 
                    'message' => 'Akses ditolak: Anda tidak memiliki wewenang untuk membuat akun dengan role Owner.'
                ], 403);
            }
        }

        DB::beginTransaction();
        try {
            $branchId = ($authUser && $authUser->role === 'owner' && $request->filled('branch_id')) 
                        ? $request->branch_id 
                        : ($authUser->branch_id ?? 1);

            $user = User::create([
                'name' => $request->name,
                'username' => $request->username, // PERBAIKAN
                'password' => Hash::make($request->password),
                'whatsapp' => $request->whatsapp,
                'role' => $request->role,
                'branch_id' => $branchId,
                'is_active' => true, 
            ]);

            $user->assignRole($request->role);

            if ($request->has('permissions') && is_array($request->permissions)) {
                $user->syncPermissions($request->permissions);
            }

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'User berhasil ditambahkan',
                'data' => User::with('permissions')->find($user->id)
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal menambahkan user: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Memperbarui user & Hak Akses
     */
    public function update(Request $request, $id)
    {
        $authUser = $request->user();

        // PERBAIKAN: Ganti email dengan username
        $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|unique:users,username,' . $id,
            'role' => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $user = User::findOrFail($id);

            if ($authUser && $authUser->role !== 'owner') {
                if ($user->branch_id !== $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki hak untuk mengubah data karyawan cabang lain.'], 403);
                }
                if ($request->filled('branch_id') && $request->branch_id != $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak diizinkan memindahkan karyawan ke cabang lain.'], 403);
                }
                if (strtolower($request->role) === 'owner' || strtolower($user->role) === 'owner') {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki wewenang untuk mengelola role atau akun Owner.'], 403);
                }
            }

            $branchId = ($authUser && $authUser->role === 'owner' && $request->filled('branch_id')) 
                        ? $request->branch_id 
                        : $user->branch_id;

            $data = [
                'name' => $request->name,
                'username' => $request->username, // PERBAIKAN
                'whatsapp' => $request->whatsapp,
                'role' => $request->role,
                'branch_id' => $branchId,
            ];
            
            if ($request->has('is_active')) {
                $data['is_active'] = $request->is_active;
            }

            if ($request->filled('password')) {
                $data['password'] = Hash::make($request->password);
            }

            $user->update($data);

            $user->syncRoles([$request->role]);

            if ($request->has('permissions') && is_array($request->permissions)) {
                $user->syncPermissions($request->permissions);
            }

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Data user berhasil diperbarui',
                'data' => User::with('permissions')->find($user->id)
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui data: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Menghapus user
     */
    public function destroy($id)
    {
        try {
            $authUser = auth()->user();
            $user = User::findOrFail($id);
            
            if ($authUser && $authUser->role !== 'owner') {
                if ($user->branch_id !== $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak berhak menghapus akun karyawan dari cabang lain.'], 403);
                }
                if (strtolower($user->role) === 'owner') {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Akun Owner tidak dapat dihapus.'], 403);
                }
            }

            if (auth()->id() == $id) {
                return response()->json(['success' => false, 'message' => 'Tidak bisa menghapus akun sendiri'], 403);
            }

            $user->delete();

            return response()->json([
                'success' => true,
                'message' => 'User berhasil dihapus'
            ], 200);
        } catch (QueryException $e) {
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal dihapus: Karyawan ini sudah memiliki riwayat pemrosesan transaksi (Jurnal/Penjualan/dll) di dalam sistem. Harap cukup nonaktifkan status akunnya alih-alih menghapusnya permanen.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus user: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * ========================================================================
     * FITUR BARU: GANTI PASSWORD KARYAWAN (USER)
     * ========================================================================
     */
    public function changePassword(Request $request)
    {
        $request->validate([
            'old_password' => 'required',
            'new_password' => 'required|min:6|confirmed',
        ]);

        $user = $request->user();

        // 1. Verifikasi Password Lama
        if (!Hash::check($request->old_password, $user->password)) {
            return response()->json([
                'success' => false, 
                'message' => 'Gagal! Password lama yang Anda masukkan salah.'
            ], 400);
        }

        // 2. Simpan Password Baru
        $user->update([
            'password' => Hash::make($request->new_password)
        ]);

        return response()->json([
            'success' => true, 
            'message' => 'Password akun Anda berhasil diperbarui dengan aman.'
        ], 200);
    }
}