<?php

namespace App\Http\Controllers;

use App\Models\EmpeduProfile;
use App\Models\EmployeeMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class EmpeduProfileController extends Controller
{
    public function index()
    {
        $profiles = EmpeduProfile::with(['employeeMaster', 'educationDegree'])
            ->where('Is_Active', true)
            ->paginate(10);
            
        return response()->json([
            'success' => true,
            'data' => $profiles
        ], 200);
    }

    public function all()
    {
        $profiles = EmpeduProfile::with(['employeeMaster', 'educationDegree'])
            ->where('Is_Active', true)
            ->get();
            
        return response()->json([
            'success' => true,
            'data' => $profiles
        ], 200);
    }

    public function show($id)
    {
        $profile = EmpeduProfile::with(['employeeMaster', 'educationDegree'])->find($id);
        
        if (!$profile) {
            return response()->json([
                'success' => false,
                'message' => 'Education profile not found'
            ], 404);
        }
        
        return response()->json([
            'success' => true,
            'data' => $profile
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Emp_Id' => 'nullable|integer|exists:employee_master,Emp_Id',
            'EEP_Date' => 'nullable|date|max:255',
            'EED_Id' => 'nullable|integer|exists:emp_edu_master,EED_Id',
            'Obtain_Grade' => 'nullable|integer',
            'Obtain_Marks' => 'nullable|integer',
            'Total_Marks' => 'nullable|integer',
            'Pass_Year' => 'nullable|string|max:7',
            'Name_Insti' => 'nullable|string|max:100',
            'Is_Active' => 'sometimes|boolean'
        ], [
            'Emp_Id.exists' => 'The selected employee ID does not exist in employee master.',
            'EED_Id.exists' => 'The selected education degree ID does not exist in education master.'
        ]);

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

        $data = $request->all();
        
        // Set default values
        if (!isset($data['Is_Active'])) {
            $data['Is_Active'] = true;
        }

        // Convert Emp_Id to integer if provided
        if (isset($data['Emp_Id']) && !empty($data['Emp_Id'])) {
            $data['Emp_Id'] = (int) $data['Emp_Id'];
        }

        // Convert EED_Id to integer if provided
        if (isset($data['EED_Id']) && !empty($data['EED_Id'])) {
            $data['EED_Id'] = (int) $data['EED_Id'];
        }

        try {
            $profile = EmpeduProfile::create($data);
            
            // Load relationships for response
            $profile->load(['employeeMaster', 'educationDegree']);
            
            return response()->json([
                'success' => true,
                'message' => 'Education profile created successfully',
                'data' => $profile
            ], 201);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create education profile',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $profile = EmpeduProfile::find($id);
        
        if (!$profile) {
            return response()->json([
                'success' => false,
                'message' => 'Education profile not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'Emp_Id' => 'nullable|integer|exists:employee_master,Emp_Id',
            'EEP_Date' => 'nullable|date|max:255',
            'EED_Id' => 'nullable|integer|exists:emp_edu_master,EED_Id',
            'Obtain_Grade' => 'nullable|integer',
            'Obtain_Marks' => 'nullable|integer',
            'Total_Marks' => 'nullable|integer',
            'Pass_Year' => 'nullable|string|max:7',
            'Name_Insti' => 'nullable|string|max:100',
            'Is_Active' => 'boolean'
        ], [
            'Emp_Id.exists' => 'The selected employee ID does not exist in employee master.',
            'EED_Id.exists' => 'The selected education degree ID does not exist in education master.'
        ]);

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

        $data = $request->all();
        
        // Convert Emp_Id to integer if provided
        if (isset($data['Emp_Id']) && !empty($data['Emp_Id'])) {
            $data['Emp_Id'] = (int) $data['Emp_Id'];
        }

        // Convert EED_Id to integer if provided
        if (isset($data['EED_Id']) && !empty($data['EED_Id'])) {
            $data['EED_Id'] = (int) $data['EED_Id'];
        }

        try {
            $profile->update($data);
            
            // Load relationships for response
            $profile->load(['employeeMaster', 'educationDegree']);
            
            return response()->json([
                'success' => true,
                'message' => 'Education profile updated successfully',
                'data' => $profile
            ], 200);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update education profile',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        $profile = EmpeduProfile::find($id);
        
        if (!$profile) {
            return response()->json([
                'success' => false,
                'message' => 'Education profile not found'
            ], 404);
        }

        try {
            $profile->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'Education profile deleted successfully'
            ], 200);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete education profile',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}