<?php

namespace App\Http\Controllers\Api;

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

/**
 * API Controller for managing Payroll 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 PayrollController 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 = Payroll::query();
        $query->with(['Employee']);
        $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(), [
            'client_id' => 'nullable|numeric',
            'employee_id' => 'nullable|integer',
            'payroll_month' => 'nullable|numeric',
            'payroll_year' => 'nullable|numeric',
            'basic_salary' => 'nullable|numeric',
            'allowances' => 'nullable|numeric',
            'deductions' => 'nullable|numeric',
            'overtime_amount' => 'nullable|numeric',
            'bonus' => 'nullable|numeric',
            'tax' => 'nullable|numeric',
            'gross_salary' => 'nullable|numeric',
            'net_salary' => 'nullable|numeric',
            'payment_status' => 'required|string|max:255',
            'payment_date' => 'nullable|date',
            'payslip' => 'required|string|max:255',
            'status' => 'required|string|max:255'
        ]);

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

        $table = new Payroll();

            $table->client_id = $request->input('client_id');
            $table->employee_id = $request->input('employee_id');
            $table->payroll_month = $request->input('payroll_month');
            $table->payroll_year = $request->input('payroll_year');
            $table->basic_salary = $request->input('basic_salary');
            $table->allowances = $request->input('allowances');
            $table->deductions = $request->input('deductions');
            $table->overtime_amount = $request->input('overtime_amount');
            $table->bonus = $request->input('bonus');
            $table->tax = $request->input('tax');
            $table->gross_salary = $request->input('gross_salary');
            $table->net_salary = $request->input('net_salary');
            $table->payment_status = $request->input('payment_status');
            $table->payment_date = $request->input('payment_date');
            $table->payslip = $request->input('payslip');
            $table->status = $request->input('status');

        $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 = Payroll::query();
        $query->with(['Employee']);
        $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 = Payroll::whereNull('deleted_at')->find($id);

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

        $validator = \Validator::make($request->all(), [
            'client_id' => 'nullable|numeric',
            'employee_id' => 'nullable|integer',
            'payroll_month' => 'nullable|numeric',
            'payroll_year' => 'nullable|numeric',
            'basic_salary' => 'nullable|numeric',
            'allowances' => 'nullable|numeric',
            'deductions' => 'nullable|numeric',
            'overtime_amount' => 'nullable|numeric',
            'bonus' => 'nullable|numeric',
            'tax' => 'nullable|numeric',
            'gross_salary' => 'nullable|numeric',
            'net_salary' => 'nullable|numeric',
            'payment_status' => 'nullable|string|max:255',
            'payment_date' => 'nullable|date',
            'payslip' => 'nullable|string|max:255',
            'status' => 'nullable|string|max:255'
        ]);

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


            $table->client_id = $request->input('client_id');
            $table->employee_id = $request->input('employee_id');
            $table->payroll_month = $request->input('payroll_month');
            $table->payroll_year = $request->input('payroll_year');
            $table->basic_salary = $request->input('basic_salary');
            $table->allowances = $request->input('allowances');
            $table->deductions = $request->input('deductions');
            $table->overtime_amount = $request->input('overtime_amount');
            $table->bonus = $request->input('bonus');
            $table->tax = $request->input('tax');
            $table->gross_salary = $request->input('gross_salary');
            $table->net_salary = $request->input('net_salary');
            $table->payment_status = $request->input('payment_status');
            $table->payment_date = $request->input('payment_date');
            $table->payslip = $request->input('payslip');
            $table->status = $request->input('status');

        $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 = Payroll::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);
    }
}
