<?php

namespace App\Http\Controllers;

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

class UsrDeptMapController extends Controller
{
    /**
     * ✅ LIST ALL MAPPINGS (with multiple departments support)
     */
    public function index()
    {
        try {
            $data = UsrDptMap::with(['user'])->get();

            // ✅ Load departments for each mapping
            $data->transform(function ($item) {
                $item->departments = $item->department_list;
                return $item;
            });

            return response()->json([
                'status' => true,
                'data'   => $data
            ]);
        } catch (\Throwable $e) {
            Log::error('UsrDeptMap INDEX Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to fetch mappings'
            ], 500);
        }
    }

    /**
     * ✅ STORE - Create new mapping (supports multiple departments)
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'Usr_Id'      => 'required|integer|exists:user_master,Usr_Id',
                'Dpt_Id'      => 'required',  // Can be single ID or array
                'Status'      => 'nullable|boolean'
            ]);

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

            // Check if mapping already exists for this user
            $existing = UsrDptMap::where('Usr_Id', $request->Usr_Id)->first();

            if ($existing) {
                return response()->json([
                    'status' => false,
                    'message' => 'Mapping already exists for this user. Use PUT to update.'
                ], 409);
            }

            // ✅ Create new mapping
            $data = UsrDptMap::create([
                'Usr_Id' => $request->Usr_Id,
                'Dpt_Id' => $request->Dpt_Id,  // Auto-handles array or single
                'Status' => $request->Status ?? 1
            ]);

            // Load departments for response
            $data->departments = $data->department_list;

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

        } catch (\Throwable $e) {
            Log::error('UsrDeptMap STORE Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to create mapping: ' . 'Something went wrong. Please try again later.'
            ], 500);
        }
    }

    /**
     * ✅ SHOW - View single mapping
     */
    public function show($id)
    {
        try {
            $data = UsrDptMap::with(['user'])->find($id);

            if (!$data) {
                return response()->json([
                    'status' => false,
                    'message' => 'Mapping not found'
                ], 404);
            }

            $data->departments = $data->department_list;

            return response()->json([
                'status' => true,
                'data' => $data
            ]);

        } catch (\Throwable $e) {
            Log::error('UsrDeptMap SHOW Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to fetch mapping'
            ], 500);
        }
    }

    /**
     * ✅ UPDATE - Update existing mapping (supports multiple departments)
     */
    public function update(Request $request, $id)
    {
        try {
            $data = UsrDptMap::find($id);

            if (!$data) {
                return response()->json([
                    'status' => false,
                    'message' => 'Mapping not found'
                ], 404);
            }

            $validator = Validator::make($request->all(), [
                'Usr_Id'      => 'sometimes|required|integer|exists:user_master,Usr_Id',
                'Dpt_Id'      => 'sometimes|required',
                'Status'      => 'nullable|boolean'
            ]);

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

            DB::beginTransaction();

            // Update fields
            if ($request->has('Usr_Id')) {
                $data->Usr_Id = $request->Usr_Id;
            }
            if ($request->has('Dpt_Id')) {
                $data->Dpt_Id = $request->Dpt_Id;  // ✅ Auto-handles array
            }
            if ($request->has('Status')) {
                $data->Status = $request->Status;
            }

            $data->save();

            DB::commit();

            $data->departments = $data->department_list;

            return response()->json([
                'status' => true,
                'message' => 'Mapping updated successfully',
                'data' => $data
            ]);

        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error('UsrDeptMap UPDATE Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to update mapping: ' . 'Something went wrong. Please try again later.'
            ], 500);
        }
    }

    /**
     * ✅ DELETE - Soft delete mapping
     */
    public function destroy($id)
    {
        try {
            $data = UsrDptMap::find($id);

            if (!$data) {
                return response()->json([
                    'status' => false,
                    'message' => 'Mapping not found'
                ], 404);
            }

            $data->delete();

            return response()->json([
                'status' => true,
                'message' => 'Mapping deleted successfully'
            ]);

        } catch (\Throwable $e) {
            Log::error('UsrDeptMap DESTROY Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to delete mapping'
            ], 500);
        }
    }

    /* ================= EXTRA HELPER METHODS ================= */

    /**
     * ✅ Get mappings by user
     */
    public function getByUser($userId)
    {
        try {
            $data = UsrDptMap::with(['user'])
                ->where('Usr_Id', $userId)
                ->first();

            if (!$data) {
                return response()->json([
                    'status' => false,
                    'message' => 'No mapping found for this user'
                ], 404);
            }

            $data->departments = $data->department_list;

            return response()->json([
                'status' => true,
                'data' => $data
            ]);

        } catch (\Throwable $e) {
            Log::error('UsrDeptMap getByUser Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to fetch user mappings'
            ], 500);
        }
    }

    /**
     * ✅ Get users by department
     */
    public function getByDepartment($deptId)
    {
        try {
            // Find all mappings that contain this department ID in Dpt_Id JSON
            $mappings = UsrDptMap::with(['user'])
                ->get()
                ->filter(function ($mapping) use ($deptId) {
                    return $mapping->hasDepartment($deptId);
                })
                ->values();

            return response()->json([
                'status' => true,
                'data' => $mappings
            ]);

        } catch (\Throwable $e) {
            Log::error('UsrDeptMap getByDepartment Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'status' => false,
                'message' => 'Failed to fetch department mappings'
            ], 500);
        }
    }
}
