<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Employee;
use Illuminate\Support\Facades\DB;

/**
 * API Controller for managing Employee resources.
 * 
 * This controller handles RESTful API operations including:
 * - Listing, creating, updating, and deleting records via API
 * - JSON response format for all endpoints
 * - Validation and error handling
 * 
 * @package App\Http\Controllers\Api
 */
class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource via API.
     * 
     * Returns a JSON response with all non-deleted records.
     * Supports eager loading of relations and custom ordering.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data array
     */
    public function index(Request $request)
    {
        $query = Employee::query();
        $query->with(['Department', 'Designation', 'Shift', 'Client']);
        $query->latest();
        $data = $query->whereNull('deleted_at')->get();

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

    /**
     * Store a newly created resource in storage via API.
     * 
     * Validates the request data and creates a new record in the database.
     * Returns JSON response with success status and created record ID.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'employee_code' => 'required|string|max:255',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:255',
            'cnic' => 'required|string|max:255',
            'gender' => 'required|string|max:255',
            'date_of_birth' => 'nullable|date',
            'joining_date' => 'nullable|date',
            'department_id' => 'nullable|integer',
            'designation_id' => 'nullable|integer',
            'shift_id' => 'nullable|integer',
            'employment_type' => 'required|string|max:255',
            'basic_salary' => 'nullable|numeric',
            'bank_name' => 'required|string|max:255',
            'bank_account_number' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'profile_picture' => 'required|string|max:255',
            'resume' => 'required|string|max:255',
            'skills' => 'required|string|max:255',
            'status' => 'required|string|max:255',
            'client_id' => 'nullable|integer'
        ]);

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

        $table = new Employee();

            $table->employee_code = $request->input('employee_code');
            $table->first_name = $request->input('first_name');
            $table->last_name = $request->input('last_name');
            $table->email = $request->input('email');
            $table->phone = $request->input('phone');
            $table->cnic = $request->input('cnic');
            $table->gender = $request->input('gender');
            $table->date_of_birth = $request->input('date_of_birth');
            $table->joining_date = $request->input('joining_date');
            $table->department_id = $request->input('department_id');
            $table->designation_id = $request->input('designation_id');
            $table->shift_id = $request->input('shift_id');
            $table->employment_type = $request->input('employment_type');
            $table->basic_salary = $request->input('basic_salary');
            $table->bank_name = $request->input('bank_name');
            $table->bank_account_number = $request->input('bank_account_number');
            $table->address = $request->input('address');
if ($request->has('profile_picture') && $request->filled('resized-profile_picture') != '') {            $table->profile_picture = $storagePath.$request->input('profile_picture');}
            $table->resume = $request->input('resume');
            $vals = $request->input('skills', []);
            if (!is_array($vals)) { $vals = []; }
            $table->skills = implode(',', array_filter(array_map('trim', array_map('strval', $vals))));
            $table->status = $request->input('status');
            $table->client_id = $request->input('client_id');

        $table->save();
        $max_id = $table->id;




        return response()->json([
            'success' => true,
            'message' => 'Record created successfully',
            'data' => ['id' => $max_id],
        ], 201);
    }

    /**
     * Display the specified resource via API.
     * 
     * Returns a JSON response with the requested record details.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to retrieve
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data, or 404 if not found
     */
    public function show(Request $request, $id)
    {
        $query = Employee::query();
        $query->with(['Department', 'Designation', 'Shift', 'Client']);
        $row = $query->whereNull('deleted_at')->find($id);

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

        return response()->json([
            'success' => true,
            'data' => $row,
        ], 200);
    }

    /**
     * Update the specified resource in storage via API.
     * 
     * Validates the request data and updates an existing record in the database.
     * Returns JSON response with success status and updated record ID.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to update
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data, or 404 if not found
     */
    public function update(Request $request, $id)
    {
        $table = Employee::whereNull('deleted_at')->find($id);

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

        $validator = \Validator::make($request->all(), [
            'employee_code' => 'nullable|string|max:255',
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:255',
            'cnic' => 'nullable|string|max:255',
            'gender' => 'nullable|string|max:255',
            'date_of_birth' => 'nullable|date',
            'joining_date' => 'nullable|date',
            'department_id' => 'nullable|integer',
            'designation_id' => 'nullable|integer',
            'shift_id' => 'nullable|integer',
            'employment_type' => 'nullable|string|max:255',
            'basic_salary' => 'nullable|numeric',
            'bank_name' => 'nullable|string|max:255',
            'bank_account_number' => 'nullable|string|max:255',
            'address' => 'nullable|string|max:255',
            'profile_picture' => 'nullable|string|max:255',
            'resume' => 'nullable|string|max:255',
            'skills' => 'nullable|string|max:255',
            'status' => 'nullable|string|max:255',
            'client_id' => 'nullable|integer'
        ]);

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


            $table->employee_code = $request->input('employee_code');
            $table->first_name = $request->input('first_name');
            $table->last_name = $request->input('last_name');
            $table->email = $request->input('email');
            $table->phone = $request->input('phone');
            $table->cnic = $request->input('cnic');
            $table->gender = $request->input('gender');
            $table->date_of_birth = $request->input('date_of_birth');
            $table->joining_date = $request->input('joining_date');
            $table->department_id = $request->input('department_id');
            $table->designation_id = $request->input('designation_id');
            $table->shift_id = $request->input('shift_id');
            $table->employment_type = $request->input('employment_type');
            $table->basic_salary = $request->input('basic_salary');
            $table->bank_name = $request->input('bank_name');
            $table->bank_account_number = $request->input('bank_account_number');
            $table->address = $request->input('address');
if ($request->has('profile_picture') && $request->filled('resized-profile_picture') != '') {            $table->profile_picture = $storagePath.$request->input('profile_picture');}
            $table->resume = $request->input('resume');
            $vals = $request->input('skills', []);
            if (!is_array($vals)) { $vals = []; }
            $table->skills = implode(',', array_filter(array_map('trim', array_map('strval', $vals))));
            $table->status = $request->input('status');
            $table->client_id = $request->input('client_id');

        $table->update();





        return response()->json([
            'success' => true,
            'message' => 'Record updated successfully',
            'data' => ['id' => (int) $id],
        ], 200);
    }

    /**
     * Remove the specified resource from storage via API.
     * 
     * Soft deletes the specified record (can be restored later).
     * Returns JSON response with success status.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to delete
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and message, or 404 if not found
     */
    public function destroy(Request $request, $id)
    {
        $row = Employee::whereNull('deleted_at')->find($id);

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

        $row->delete();

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