<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\Session;
use Illuminate\Http\Request;

class AdminEmployeeController extends Controller
{
    /**
     * Show session-wise employee listing.
     */
    public function index(Request $request)
    {
        // All sessions for filter dropdown
        $sessions = Session::orderBy('start_date', 'desc')->get();

        // session filter from query or active session fallback
        $sessionId = $request->get('session_id') ?? (Session::active()?->id ?? null);

        // status filter from query: 'active', 'inactive' or null
        $status = $request->get('status'); // ?status=active or ?status=inactive

        // Load employees, eager load sessions + linked user if exists
        $query = Employee::with(['sessions', 'user']);

        // If session filter requested, only employees attached to that session
        if ($sessionId) {
            $query->whereHas('sessions', function ($q) use ($sessionId) {
                $q->where('financial_sessions.id', $sessionId);
            });
        }

        // Global employee active/inactive filter
        if ($status === 'active') {
            $query->where('is_active', true);
        } elseif ($status === 'inactive') {
            $query->where('is_active', false);
        }

        // Paginate results
        $employees = $query->orderBy('name')->paginate(10)->withQueryString();

        return view('admin.employees.index', compact('employees', 'sessions', 'sessionId', 'status'));
    }

    /**
     * Show create form.
     */
    public function create()
    {
        $sessions = Session::orderBy('start_date', 'desc')->get();
        return view('admin.employees.create', compact('sessions'));
    }

    /**
     * Store new employee + attach to session.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'       => 'required',
            'email'      => 'required|email|unique:employees,email',
            'phone'      => 'required|unique:employees,phone',
            'session_id' => 'required|exists:financial_sessions,id',
        ]);

        $employee = Employee::create($request->only('name', 'email', 'phone'));

        $employee->sessions()->attach($request->session_id, [
            'joined_at'             => now(),
            'is_active_for_session' => true,
        ]);

        return redirect()->route('admin.employees.index')
            ->with('success', 'Employee added & assigned to session.');
    }

    /**
     * Show edit form for an employee.
     */
    public function edit(Employee $employee)
    {
        $sessions = Session::orderBy('start_date', 'desc')->get();
        $employeeSessionIds = $employee->sessions->pluck('id')->toArray();

        return view('admin.employees.edit', compact('employee', 'sessions', 'employeeSessionIds'));
    }

    /**
     * Update employee basic info + (optionally) sessions.
     */
    public function update(Request $request, Employee $employee)
    {
        $request->validate([
            'name'  => 'required',
            'email' => 'required|email|unique:employees,email,' . $employee->id,
            'phone' => 'required|unique:employees,phone,' . $employee->id,
            'is_active' => 'nullable|boolean',
            // sessions are optional here; you can manage via separate UI if you prefer
            'session_ids' => 'nullable|array',
            'session_ids.*' => 'exists:financial_sessions,id',
        ]);

        $employee->name      = $request->name;
        $employee->email     = $request->email;
        $employee->phone     = $request->phone;
        $employee->is_active = $request->boolean('is_active');
        $employee->save();

        // Sync sessions if provided
        if ($request->filled('session_ids')) {
            $syncData = [];
            foreach ($request->session_ids as $sid) {
                $syncData[$sid] = [
                    'joined_at'             => now(),
                    'is_active_for_session' => true,
                ];
            }
            $employee->sessions()->sync($syncData);
        }

        // Sync linked user (if exists)
        if ($employee->user) {
            $employee->user->name      = $employee->name;
            $employee->user->email     = $employee->email;
            $employee->user->phone     = $employee->phone;
            $employee->user->is_active = $employee->is_active;
            $employee->user->save();
        }

        return redirect()->route('admin.employees.index')
            ->with('success', 'Employee updated successfully.');
    }

    /**
     * Delete employee (cascades pivot; login blocked because employee record gone).
     */
    public function destroy(Employee $employee)
    {
        // Optionally deactivate linked user account instead of deleting it
        if ($employee->user) {
            $employee->user->is_active   = false;
            $employee->user->employee_id = null;
            $employee->user->save();
        }

        $employeeName = $employee->name;
        $employee->delete();

        return redirect()->route('admin.employees.index')
            ->with('success', "Employee {$employeeName} deleted.");
    }

    /**
     * Attach an existing employee to a session.
     */
    public function attachSession(Request $request, $employeeId)
    {
        $request->validate([
            'session_id' => 'required|exists:financial_sessions,id',
        ]);

        $employee = Employee::findOrFail($employeeId);

        $employee->sessions()->syncWithoutDetaching([
            $request->session_id => [
                'joined_at'             => now(),
                'is_active_for_session' => true,
            ],
        ]);

        return back()->with('success', 'Employee attached to session.');
    }

    /**
     * Toggle global active/inactive flag for employee.
     * Also syncs linked user.is_active (if exists).
     */
    public function toggleActive(Employee $employee)
    {
        // Flip the is_active flag
        $employee->is_active = ! $employee->is_active;
        $employee->save();

        // If this employee has a linked user, sync that flag too
        if ($employee->user) {
            $employee->user->is_active = $employee->is_active;
            $employee->user->save();
        }

        $statusText = $employee->is_active ? 'activated' : 'deactivated';

        return back()->with('success', "Employee {$employee->name} has been {$statusText}.");
    }
}
