<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MeterReader;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class MeterReaderController extends Controller
{
    /**
     * Display a listing of meter readers.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            // Check if user is authenticated and has a company
            $companyId = null;
            if ($request->user()) {
                $companyId = $request->user()->CompanyID ?? $request->user()->company_id;
            }

            // Query meter readers - filter by company if authenticated, otherwise return all
            $query = MeterReader::with(['company', 'property'])
                ->select([
                    'id',
                    'username',
                    'first_name',
                    'last_name',
                    'email',
                    'phone_number',
                    'company_id',
                    'PropID',
                    'created_at',
                    'updated_at'
                ]);

            // Apply company filter if user is authenticated and has a company
            if ($companyId) {
                $query->where('company_id', $companyId);
            }

            $meterReaders = $query->orderBy('first_name')
                ->orderBy('last_name')
                ->get();

            // Format the response
            $formattedMeterReaders = $meterReaders->map(function ($meterReader) {
                return [
                    'id' => $meterReader->id,
                    'username' => $meterReader->username,
                    'full_name' => $meterReader->first_name . ' ' . $meterReader->last_name,
                    'first_name' => $meterReader->first_name,
                    'last_name' => $meterReader->last_name,
                    'email' => $meterReader->email,
                    'phone_number' => $meterReader->phone_number,
                    'prop_id' => $meterReader->property ? $meterReader->property->PropID : null,
                    'prop_name' => $meterReader->property ? $meterReader->property->PropName : null,
                    'company_id' => $meterReader->company ? $meterReader->company->CompanyID : null,
                    'company_name' => $meterReader->company ? $meterReader->company->CompanyName : null,
                
                ];
            });

            return response()->json([
                'success' => true,
                'message' => 'Meter readers retrieved successfully',
                'data' => $formattedMeterReaders
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving meter readers: ' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }
}
