<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\PropertyMaster;
use Illuminate\Http\Request;

class PropertyMasterController extends Controller
{
  public function index(Request $request)
{
    $perPage = $request->per_page ?? 10;
    $search  = $request->search;

    $query = PropertyMaster::with([
        'ward',
        'zone',
        'owner',
        'usageType',
        'constructionType',
        'occupancyStatus'
    ]);

    // Search
    if (!empty($search)) {
        $query->where(function ($q) use ($search) {
            $q->where('Prop_No', 'like', "%{$search}%")
              ->orWhere('Old_Prop_No', 'like', "%{$search}%")
              ->orWhere('Prop_Name', 'like', "%{$search}%")
              ->orWhere('Plot_No', 'like', "%{$search}%")
              ->orWhere('Survey_No', 'like', "%{$search}%")
              ->orWhere('CTS_No', 'like', "%{$search}%")
              ->orWhere('Address_Line1', 'like', "%{$search}%")
              ->orWhere('Address_Line2', 'like', "%{$search}%")
              ->orWhere('Pincode', 'like', "%{$search}%")
              ->orWhere('Status', 'like', "%{$search}%");
        });
    }

    // Filters
    if ($request->filled('Ward_Id')) {
        $query->where('Ward_Id', $request->Ward_Id);
    }

    if ($request->filled('Zone_Id')) {
        $query->where('Zone_Id', $request->Zone_Id);
    }

    if ($request->filled('Owner_Id')) {
        $query->where('Owner_Id', $request->Owner_Id);
    }

    if ($request->filled('UsgTy_Id')) {
        $query->where('UsgTy_Id', $request->UsgTy_Id);
    }

    if ($request->filled('ConsTy_Id')) {
        $query->where('ConsTy_Id', $request->ConsTy_Id);
    }

    if ($request->filled('Occp_Id')) {
        $query->where('Occp_Id', $request->Occp_Id);
    }

    if ($request->filled('Status')) {
        $query->where('Status', $request->Status);
    }

    if ($request->filled('Is_Exempt')) {
        $query->where('Is_Exempt', $request->Is_Exempt);
    }

    if ($request->filled('Has_Parking')) {
        $query->where('Has_Parking', $request->Has_Parking);
    }

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

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


/**
 * All Data (No Pagination) + Search + Filters
 */
public function all(Request $request)
{
    $search = $request->search;

    $query = PropertyMaster::with([
        'ward',
        'zone',
        'owner',
        'usageType',
        'constructionType',
        'occupancyStatus'
    ]);

    // Search
    if (!empty($search)) {
        $query->where(function ($q) use ($search) {
            $q->where('Prop_No', 'like', "%{$search}%")
              ->orWhere('Old_Prop_No', 'like', "%{$search}%")
              ->orWhere('Prop_Name', 'like', "%{$search}%")
              ->orWhere('Plot_No', 'like', "%{$search}%")
              ->orWhere('Survey_No', 'like', "%{$search}%")
              ->orWhere('CTS_No', 'like', "%{$search}%")
              ->orWhere('Address_Line1', 'like', "%{$search}%")
              ->orWhere('Address_Line2', 'like', "%{$search}%")
              ->orWhere('Pincode', 'like', "%{$search}%")
              ->orWhere('Status', 'like', "%{$search}%");
        });
    }

    // Filters
    if ($request->filled('Ward_Id')) {
        $query->where('Ward_Id', $request->Ward_Id);
    }

    if ($request->filled('Zone_Id')) {
        $query->where('Zone_Id', $request->Zone_Id);
    }

    if ($request->filled('Owner_Id')) {
        $query->where('Owner_Id', $request->Owner_Id);
    }

    if ($request->filled('UsgTy_Id')) {
        $query->where('UsgTy_Id', $request->UsgTy_Id);
    }

    if ($request->filled('ConsTy_Id')) {
        $query->where('ConsTy_Id', $request->ConsTy_Id);
    }

    if ($request->filled('Occp_Id')) {
        $query->where('Occp_Id', $request->Occp_Id);
    }

    if ($request->filled('Status')) {
        $query->where('Status', $request->Status);
    }

    $data = $query->orderBy('Prop_Id', 'desc')->get();

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

    // Store
    public function store(Request $request)
    {
     $request->validate([
    // 'Prop_No'             => 'required|unique:property_master,Prop_No',
    'Prop_No' => [
            'nullable',
            \Illuminate\Validation\Rule::unique('property_master', 'Prop_No')
                ->whereNull('deleted_at')
        ],
    'Old_Prop_No'         => 'nullable|string|max:30',

    'Ward_Id'             => 'nullable|exists:ward_master,Wrd_Id',
    'Zone_Id'             => 'nullable|exists:zone_master,Zon_Id',
    'Owner_Id'            => 'nullable|exists:owner_master,Owner_ID',

    'Prop_Name'           => 'nullable|string|max:200',
    'Plot_No'             => 'nullable|string|max:50',
    'Survey_No'           => 'nullable|string|max:50',
    'CTS_No'              => 'nullable|string|max:50',

    'Address_Line1'       => 'required|string|max:255',
    'Address_Line2'       => 'nullable|string|max:255',
    'Pincode'             => 'nullable|string|max:10',

    'Latitude'            => 'nullable|numeric',
    'Longitude'           => 'nullable|numeric',

    'UsgTy_Id'            => 'nullable|exists:property_usage_types,UsgTy_Id',
    'ConsTy_Id'           => 'nullable|exists:construction_types,ConsTy_Id',
    'Occp_Id'             => 'nullable|exists:occupancy_status,Occp_Id',

    'Total_Area'          => 'required|numeric',
    'Built_Area'          => 'required|numeric',
    'Carpet_Area'         => 'nullable|numeric',

    'Floor_No'            => 'nullable|integer',
    'Total_Floors'        => 'nullable|integer',

    'Year_Built'          => 'nullable|digits:4|integer',
    'Age_Factor'          => 'nullable|numeric',

    'Capital_Value'       => 'nullable|numeric',
    'Annual_Rent_Value'   => 'nullable|numeric',

    'Is_Corner'           => 'nullable|boolean',
    'Has_Parking'         => 'nullable|boolean',

    'Parking_Area'        => 'nullable|numeric',

    'Is_Exempt'           => 'nullable|boolean',
    'Exempt_Reason'       => 'nullable|string|max:255',

    'Status'              => 'nullable|in:Active,Merged,Bifurcated,Demolished,Disputed',
]);

        $data = PropertyMaster::create($request->all());

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

    // Show Single
    public function show($id)
    {
        $data = PropertyMaster::with([
            'ward',
            'zone',
            'owner',
            'usageType',
            'constructionType',
            'occupancyStatus'
        ])->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 = PropertyMaster::find($id);

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

        $request->validate([
            // 'Prop_No'           => 'nullable|unique:property_master,Prop_No,' . $id . ',Prop_Id',
            'Prop_No' => [
                'nullable',
                \Illuminate\Validation\Rule::unique('property_master', 'Prop_No')
                    ->ignore($id, 'Prop_Id')
                    ->whereNull('deleted_at')
            ],
            'Old_Prop_No'       => 'nullable',
            'Ward_Id'           => 'nullable',
            'Zone_Id'           => 'nullable',
            'Owner_Id'          => 'nullable',
            'Prop_Name'         => 'nullable',
            'Plot_No'           => 'nullable',
            'Survey_No'         => 'nullable',
            'CTS_No'            => 'nullable',
            'Address_Line1'     => 'nullable',
            'Address_Line2'     => 'nullable',
            'Pincode'           => 'nullable',
            'Latitude'          => 'nullable',
            'Longitude'         => 'nullable',
            'UsgTy_Id'          => 'nullable',
            'ConsTy_Id'         => 'nullable',
            'Occp_Id'           => 'nullable',
            'Total_Area'        => 'nullable|numeric',
            'Built_Area'        => 'nullable|numeric',
            'Carpet_Area'       => 'nullable|numeric',
            'Floor_No'          => 'nullable',
            'Total_Floors'      => 'nullable',
            'Year_Built'        => 'nullable',
            'Age_Factor'        => 'nullable|numeric',
            'Capital_Value'     => 'nullable|numeric',
            'Annual_Rent_Value' => 'nullable|numeric',
            'Is_Corner'         => 'nullable',
            'Has_Parking'       => 'nullable',
            'Parking_Area'      => 'nullable|numeric',
            'Is_Exempt'         => 'nullable',
            'Exempt_Reason'     => 'nullable',
            'Status'            => 'nullable'
        ]);

        $updateData = [];

        foreach ($request->all() as $key => $value) {
            $updateData[$key] = $value;
        }

        $data->update($updateData);

        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 = PropertyMaster::find($id);

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

        $data->delete();

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