<?php

namespace App\Http\Controllers\Superadmin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\School;
use App\Models\Employee;
use App\Models\EmployeeAssignment;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserSchoolMappingController extends Controller
{
    /**
     * Display a listing of user-school mappings
     */
    public function index(Request $request)
    {
        $query = User::with(['role', 'employee.activeAssignment.school']);

        // Filter by role
        if ($request->filled('role_id')) {
            $query->where('role_id', $request->role_id);
        }

        // Filter by school
        if ($request->filled('school_id')) {
            $query->whereHas('employee.activeAssignment', function($q) use ($request) {
                $q->where('school_id', $request->school_id);
            });
        }

        // Search by name or email
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $users = $query->paginate(20);
        $roles = Role::whereIn('slug', ['admin_sekolah', 'kepala_sekolah', 'guru', 'pengawas'])->get();
        $schools = School::orderBy('name')->get();

        return view('superadmin.user-school-mapping.index', compact('users', 'roles', 'schools'));
    }

    /**
     * Show form to map user to school
     */
    public function create()
    {
        $users = User::whereHas('role', function($q) {
                $q->whereIn('slug', ['admin_sekolah', 'kepala_sekolah', 'guru', 'pengawas']);
            })
            ->orderBy('name')
            ->get();

        $schools = School::orderBy('name')->get();

        return view('superadmin.user-school-mapping.create', compact('users', 'schools'));
    }

    /**
     * Store a newly created mapping
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'school_id' => 'required|exists:schools,id',
            'nip' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:20',
            'start_date' => 'required|date',
            'position' => 'nullable|string|max:100',
        ]);

        DB::beginTransaction();
        try {
            $user = User::findOrFail($request->user_id);

            // Create or get employee record
            if ($user->employee_id) {
                // User already has employee
                $employee = Employee::findOrFail($user->employee_id);
                
                // Update employee data
                $employee->update([
                    'nip' => $request->nip ?? $employee->nip,
                    'phone' => $request->phone ?? $employee->phone,
                ]);
            } else {
                // Create new employee
                $employee = Employee::create([
                    'name' => $user->name,
                    'nip' => $request->nip,
                    'phone' => $request->phone,
                    'email' => $user->email,
                    'is_active' => true
                ]);
                
                // Link user to employee
                $user->update(['employee_id' => $employee->id]);
            }

            // Deactivate all previous assignments for this employee
            EmployeeAssignment::where('employee_id', $employee->id)
                ->where('is_active', true)
                ->update(['is_active' => false, 'end_date' => now()]);

            // Create new assignment
            EmployeeAssignment::create([
                'employee_id' => $employee->id,
                'assignment_type' => EmployeeAssignment::TYPE_SCHOOL,
                'school_id' => $request->school_id,
                'start_date' => $request->start_date,
                'notes' => $request->position,
                'is_active' => true,
            ]);

            DB::commit();

            return redirect()->route('superadmin.user-school-mapping.index')
                ->with('success', 'User berhasil dipetakan ke sekolah.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error mapping user to school', [
                'error' => $e->getMessage(),
                'user_id' => $request->user_id
            ]);

            return back()->withInput()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Show form to edit mapping
     */
    public function edit($id)
    {
        $user = User::with(['employee.activeAssignment'])->findOrFail($id);
        
        if (!$user->employee) {
            return redirect()->route('superadmin.user-school-mapping.index')
                ->with('error', 'User ini belum memiliki mapping.');
        }

        $schools = School::orderBy('name')->get();

        return view('superadmin.user-school-mapping.edit', compact('user', 'schools'));
    }

    /**
     * Update the mapping
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'school_id' => 'required|exists:schools,id',
            'nip' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:20',
            'start_date' => 'required|date',
            'position' => 'nullable|string|max:100',
        ]);

        DB::beginTransaction();
        try {
            $user = User::findOrFail($id);
            
            if (!$user->employee_id) {
                throw new \Exception('User belum memiliki employee record');
            }
            
            $employee = Employee::findOrFail($user->employee_id);

            // Update employee data
            $employee->update([
                'nip' => $request->nip,
                'phone' => $request->phone,
            ]);

            $currentAssignment = $employee->activeAssignment;

            // Check if school changed
            if (!$currentAssignment || $currentAssignment->school_id != $request->school_id) {
                // Deactivate current assignment if exists
                if ($currentAssignment) {
                    $currentAssignment->update([
                        'is_active' => false,
                        'end_date' => now()
                    ]);
                }

                // Create new assignment
                EmployeeAssignment::create([
                    'employee_id' => $employee->id,
                    'assignment_type' => EmployeeAssignment::TYPE_SCHOOL,
                    'school_id' => $request->school_id,
                    'start_date' => $request->start_date,
                    'notes' => $request->position,
                    'is_active' => true,
                ]);
            } else {
                // Just update the existing assignment
                $currentAssignment->update([
                    'start_date' => $request->start_date,
                    'notes' => $request->position,
                ]);
            }

            DB::commit();

            return redirect()->route('superadmin.user-school-mapping.index')
                ->with('success', 'Mapping berhasil diperbarui.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error updating user-school mapping', [
                'error' => $e->getMessage(),
                'user_id' => $id
            ]);

            return back()->withInput()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Remove the mapping
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $user = User::findOrFail($id);
            
            if ($user->employee_id) {
                $employee = Employee::find($user->employee_id);
                
                if ($employee) {
                    $activeAssignment = $employee->activeAssignment;
                    
                    if ($activeAssignment) {
                        $activeAssignment->update([
                            'is_active' => false,
                            'end_date' => now()
                        ]);
                    }
                }
            }

            DB::commit();

            return redirect()->route('superadmin.user-school-mapping.index')
                ->with('success', 'Mapping berhasil dihapus.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }
}
