<?php

namespace App\Http\Controllers;

use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class DepartmentController extends Controller
{
    /**
     * Display a listing of departments with optional filters
     */
    public function index(Request $request)
    {
        try {
            $query = Department::query();

            // Filter by GrStt if provided
            if ($request->has('gr_stt')) {
                $types = explode(',', $request->gr_stt);
                $query->whereIn('GrStt', $types);
            }

            // Search
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('Dpt_Desc', 'like', '%' . $search . '%')
                      ->orWhere('Dpt_Name', 'like', '%' . $search . '%')
                      ->orWhere('GrCod', 'like', '%' . $search . '%');
                });
            }

            // Order by
            $orderBy = $request->get('order_by', 'Dpt_id');
            $orderDirection = $request->get('order_dir', 'asc');
            $query->orderBy($orderBy, $orderDirection);

            // Pagination
            $perPage = $request->get('per_page', 25);
            $departments = $query->paginate($perPage);

            $uniqueTypes = Department::select('GrStt')->distinct()->pluck('GrStt');

            return response()->json([
                'success' => true,
                'message' => 'Departments retrieved successfully',
                'data' => $departments->items(),
                'available_types' => $uniqueTypes,
                'pagination' => [
                    'total' => $departments->total(),
                    'per_page' => $departments->perPage(),
                    'current_page' => $departments->currentPage(),
                    'last_page' => $departments->lastPage(),
                    'from' => $departments->firstItem(),
                    'to' => $departments->lastItem()
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve departments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all departments
     */
    public function getAllDepartments(Request $request)
    {
        try {
            $query = Department::query();

            if ($request->has('gr_stt')) {
                $types = explode(',', $request->gr_stt);
                $query->whereIn('GrStt', $types);
            }

            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('Dpt_Desc', 'like', '%' . $search . '%')
                      ->orWhere('Dpt_Name', 'like', '%' . $search . '%');
                });
            }

            $orderBy = $request->get('order_by', 'Dpt_id');
            $orderDirection = $request->get('order_dir', 'asc');
            $query->orderBy($orderBy, $orderDirection);

            $departments = $query->get();

            return response()->json([
                'success' => true,
                'message' => 'All departments retrieved successfully',
                'data' => $departments,
                'count' => $departments->count()
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve all departments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a newly created department
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'Dpt_Desc' => 'required|string|max:255',
                'Dpt_Name' => 'nullable|string|max:255',
                'GrCod' => 'nullable|string|max:255',
                'UpGrp' => 'nullable|string|max:255',
                'GrSrn' => 'nullable|string|max:255',
                'GrStt' => 'nullable|string|max:255',
                'isvisible' => 'required|integer|in:0,1'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $department = Department::create($request->only([
                'Dpt_Desc',
                'Dpt_Name',
                'GrCod',
                'UpGrp',
                'GrSrn',
                'GrStt',
                'isvisible'
            ]));

            return response()->json([
                'success' => true,
                'message' => 'Department created successfully',
                'data' => $department
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create department',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified department
     */
    public function show($id)
    {
        $department = Department::find($id);

        if (!$department) {
            return response()->json([
                'success' => false,
                'message' => 'Department not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Department retrieved successfully',
            'data' => $department
        ]);
    }

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

        if (!$department) {
            return response()->json([
                'success' => false,
                'message' => 'Department not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'Dpt_Desc' => 'sometimes|required|string|max:255',
            'Dpt_Name' => 'sometimes|nullable|string|max:255',
            'GrCod' => 'sometimes|nullable|string|max:255',
            'UpGrp' => 'sometimes|nullable|string|max:255',
            'GrSrn' => 'sometimes|nullable|string|max:255',
            'GrStt' => 'sometimes|nullable|string|max:255',
            'isvisible' => 'sometimes|required|integer|in:0,1'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $department->update($request->only([
            'Dpt_Desc',
            'Dpt_Name',
            'GrCod',
            'UpGrp',
            'GrSrn',
            'GrStt',
            'isvisible'
        ]));

        return response()->json([
            'success' => true,
            'message' => 'Department updated successfully',
            'data' => $department
        ]);
    }

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

        if (!$department) {
            return response()->json([
                'success' => false,
                'message' => 'Department not found'
            ], 404);
        }

        $department->delete();

        return response()->json([
            'success' => true,
            'message' => 'Department deleted successfully'
        ]);
    }
}
