<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Department;
use App\Models\NotificationTemplate;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class SettingsController extends Controller
{
    public function index()
    {
        $team = User::orderBy('full_name')->get();
        $departments = Department::orderBy('name')->get();
        $notifications = NotificationTemplate::all();

        return view('dashboard.settings.index', compact('team', 'departments', 'notifications'));
    }

    public function saveTeamUser(Request $request)
    {
        $userId = $request->input('id');

        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users')->ignore($userId),
            ],
            'password' => $userId ? 'nullable|string|min:8' : 'required|string|min:8',
            'role' => 'required|in:admin,hr_manager,hiring_manager,interviewer,viewer',
            'department' => 'nullable|string|max:100',
        ]);

        return DB::transaction(function () use ($validated, $userId, $request) {
            $data = [
                'full_name' => $validated['full_name'],
                'email' => $validated['email'],
                'role' => $validated['role'],
                'department' => $validated['department'],
            ];

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

            if ($userId) {
                $user = User::findOrFail($userId);
                $user->update($data);
                $action = 'team_user_updated';
            } else {
                $user = User::create(array_merge($data, ['is_active' => true]));
                $action = 'team_user_created';
            }

            AuditLog::log(
                actorId: Auth::id(),
                action: $action,
                entityType: User::class,
                entityId: $user->id,
                details: ['email' => $user->email]
            );

            return redirect()->route('settings.index')->with('success', 'Team member details saved.');
        });
    }

    public function toggleTeamUser($id)
    {
        $user = User::findOrFail($id);

        if ($user->id === Auth::id()) {
            return back()->withErrors(['error' => 'You cannot deactivate your own account.']);
        }

        $user->update([
            'is_active' => !$user->is_active
        ]);

        $statusLabel = $user->is_active ? 'activated' : 'deactivated';

        AuditLog::log(
            actorId: Auth::id(),
            action: 'team_user_toggle_status',
            entityType: User::class,
            entityId: $user->id,
            details: ['status' => $statusLabel]
        );

        return redirect()->route('settings.index')->with('success', "Team member has been {$statusLabel}.");
    }

    public function saveDepartment(Request $request)
    {
        $deptId = $request->input('id');

        $validated = $request->validate([
            'name' => [
                'required',
                'string',
                'max:100',
                Rule::unique('departments')->ignore($deptId),
            ],
            'description' => 'nullable|string|max:500',
        ]);

        $dept = Department::updateOrCreate([
            'id' => $deptId
        ], [
            'name' => $validated['name'],
            'description' => $validated['description'],
        ]);

        $action = $deptId ? 'department_updated' : 'department_created';

        AuditLog::log(
            actorId: Auth::id(),
            action: $action,
            entityType: Department::class,
            entityId: $dept->id,
            details: ['name' => $dept->name]
        );

        return redirect()->route('settings.index')->with('success', 'Department details saved.');
    }

    public function toggleDepartment($id)
    {
        $dept = Department::findOrFail($id);

        $dept->update([
            'is_active' => !$dept->is_active
        ]);

        $statusLabel = $dept->is_active ? 'activated' : 'deactivated';

        AuditLog::log(
            actorId: Auth::id(),
            action: 'department_toggle_status',
            entityType: Department::class,
            entityId: $dept->id,
            details: ['status' => $statusLabel]
        );

        return redirect()->route('settings.index')->with('success', "Department has been {$statusLabel}.");
    }

    public function saveNotificationTemplate(Request $request, $id)
    {
        $template = NotificationTemplate::findOrFail($id);

        $validated = $request->validate([
            'sms_body' => 'required|string|max:500',
            'whatsapp_body' => 'required|string|max:2000',
        ]);

        $template->update([
            'sms_body' => $validated['sms_body'],
            'whatsapp_body' => $validated['whatsapp_body'],
        ]);

        AuditLog::log(
            actorId: Auth::id(),
            action: 'notification_template_updated',
            entityType: NotificationTemplate::class,
            entityId: $template->id,
            details: ['event_key' => $template->event_key]
        );

        return redirect()->route('settings.index')->with('success', 'Notification template updated successfully.');
    }
}
