<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class TeacherController extends ApiController
{
    /**
     * Display a listing of teachers with pagination and search
     */
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $search = $request->get('search');
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');

        $query = Teacher::with(['school', 'subjects']);

        // Apply search
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('last_name', 'like', "%{$search}%")
                  ->orWhere('employee_id', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // Apply filters
        if ($request->has('department') && $request->department) {
            $query->where('department', $request->department);
        }

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

        // Apply sorting
        $query = $this->applySorting($query, $sortBy, $sortOrder);

        return $this->paginatedResponse($query, $perPage);
    }

    /**
     * Store a newly created teacher
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'school_id' => 'required|exists:schools,id',
            'employee_id' => 'required|unique:teachers,employee_id',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:male,female,other',
            'email' => 'required|email|unique:teachers,email',
            'password' => 'required|string|min:8',
            'phone' => 'required|string',
            'address' => 'nullable|string',
            'city' => 'nullable|string',
            'state' => 'nullable|string',
            'country' => 'nullable|string',
            'pincode' => 'nullable|string',
            'photo' => 'nullable|string',
            'qualification' => 'nullable|string',
            'experience_years' => 'nullable|integer',
            'joining_date' => 'required|date',
            'department' => 'nullable|string',
            'designation' => 'nullable|string',
            'salary' => 'nullable|numeric',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $data = $request->all();
        $data['password'] = Hash::make($request->password);

        $teacher = Teacher::create($data);

        return $this->successResponse(
            $teacher->load('school'),
            'Teacher created successfully',
            201
        );
    }

    /**
     * Display the specified teacher
     */
    public function show($id)
    {
        $teacher = Teacher::with(['school', 'subjects', 'classTeacher'])->find($id);

        if (!$teacher) {
            return $this->errorResponse('Teacher not found', 404);
        }

        return $this->successResponse($teacher);
    }

    /**
     * Update the specified teacher
     */
    public function update(Request $request, $id)
    {
        $teacher = Teacher::find($id);

        if (!$teacher) {
            return $this->errorResponse('Teacher not found', 404);
        }

        $validator = Validator::make($request->all(), [
            'school_id' => 'sometimes|exists:schools,id',
            'employee_id' => 'sometimes|unique:teachers,employee_id,' . $id,
            'first_name' => 'sometimes|string|max:255',
            'last_name' => 'sometimes|string|max:255',
            'date_of_birth' => 'sometimes|date',
            'gender' => 'sometimes|in:male,female,other',
            'email' => 'sometimes|email|unique:teachers,email,' . $id,
            'password' => 'nullable|string|min:8',
            'phone' => 'sometimes|string',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $data = $request->except('password');

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

        $teacher->update($data);

        return $this->successResponse(
            $teacher->load('school'),
            'Teacher updated successfully'
        );
    }

    /**
     * Remove the specified teacher
     */
    public function destroy($id)
    {
        $teacher = Teacher::find($id);

        if (!$teacher) {
            return $this->errorResponse('Teacher not found', 404);
        }

        $teacher->delete();

        return $this->successResponse(null, 'Teacher deleted successfully');
    }

    /**
     * Get teacher's schedule/timetable
     */
    public function schedule(Request $request, $id)
    {
        $teacher = Teacher::find($id);

        if (!$teacher) {
            return $this->errorResponse('Teacher not found', 404);
        }

        $dayOfWeek = $request->get('day');

        $query = $teacher->timetables()->with(['class', 'section', 'subject', 'period']);

        if ($dayOfWeek) {
            $query->where('day_of_week', $dayOfWeek);
        }

        $schedule = $query->orderBy('day_of_week')->orderBy('period_id')->get();

        return $this->successResponse($schedule);
    }
}
