<?php

namespace App\Http\Controllers;

use App\Models\PropertyUsageType;
use Illuminate\Http\Request;

class PropertyUsageTypeController extends Controller
{
    /**
     * INDEX
     * Search + Pagination
     */
    public function index(Request $request)
    {
        try {
            $perPage = $request->per_page ?? 10;
            $search  = $request->search;

            $query = PropertyUsageType::query();

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {
                    $q->where('UsgTy_Code', 'like', "%{$search}%")
                      ->orWhere('UsgTy_Name', 'like', "%{$search}%")
                      ->orWhere('UsgTy_Category', 'like', "%{$search}%")
                      ->orWhere('Use_Factor', 'like', "%{$search}%");
                });
            }

            $data = $query->orderBy('UsgTy_Id', 'desc')->paginate($perPage);

            return response()->json([
                'status'  => true,
                'message' => 'Property Usage Type List',
                'data'    => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => 'Something went wrong. Please try again later.'
            ]);
        }
    }

    /**
     * ALL DATA
     * Without Pagination
     */
    public function allData()
    {
        try {
            $data = PropertyUsageType::orderBy('UsgTy_Id', 'desc')->get();

            return response()->json([
                'status'  => true,
                'message' => 'All Property Usage Type Data',
                'count'   => $data->count(),
                'data'    => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => 'Something went wrong. Please try again later.'
            ]);
        }
    }

    /**
     * STORE
     */
   public function store(Request $request)
{
    $request->validate([
        'UsgTy_Code' => [
            'nullable',
            \Illuminate\Validation\Rule::unique('property_usage_types', 'UsgTy_Code')
                ->whereNull('deleted_at')
        ],
        'UsgTy_Name'     => 'required',
        'UsgTy_Category' => 'required|in:Residential,Commercial,Industrial,Mixed,Exempt',
        'Use_Factor'     => 'nullable|numeric'
    ]);

    $data = PropertyUsageType::create([
        'UsgTy_Code'     => $request->UsgTy_Code,
        'UsgTy_Name'     => $request->UsgTy_Name,
        'UsgTy_Category' => $request->UsgTy_Category,
        'Use_Factor'     => $request->Use_Factor ?? 1.00
    ]);

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

    /**
     * SHOW SINGLE
     */
    public function show($id)
    {
        $data = PropertyUsageType::find($id);

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

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

    /**
     * UPDATE
     */
public function update(Request $request, $id)
{
    try {

        $data = PropertyUsageType::where('UsgTy_Id', $id)->first();

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

        $request->validate([
            'UsgTy_Code' => [
                'nullable',
                \Illuminate\Validation\Rule::unique('property_usage_types', 'UsgTy_Code')
                    ->ignore($id, 'UsgTy_Id')
                    ->whereNull('deleted_at')
            ],
            'UsgTy_Name' => 'nullable',
            'UsgTy_Category' => 'nullable',
            'Use_Factor' => 'nullable|numeric'
        ]);

        $data->update([
            'UsgTy_Code'     => $request->filled('UsgTy_Code') ? $request->UsgTy_Code : $data->UsgTy_Code,
            'UsgTy_Name'     => $request->filled('UsgTy_Name') ? $request->UsgTy_Name : $data->UsgTy_Name,
            'UsgTy_Category' => $request->filled('UsgTy_Category') ? $request->UsgTy_Category : $data->UsgTy_Category,
            'Use_Factor'     => $request->filled('Use_Factor') ? $request->Use_Factor : $data->Use_Factor,
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Updated Successfully',
            'data' => $data->fresh()
        ], 200);

    } catch (\Illuminate\Validation\ValidationException $e) {

        return response()->json([
            'status' => false,
            'message' => $e->errors()
        ], 422);

    } catch (\Exception $e) {

        return response()->json([
            'status' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}
    /**
     * DELETE
     */
    public function destroy($id)
    {
        $data = PropertyUsageType::find($id);

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

        $data->delete();

        return response()->json([
            'status'  => true,
            'message' => 'Deleted Successfully'
        ]);
    }
}
