<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\TmpMeterReading;
use App\Models\Company;
use App\Models\Property;
use App\Models\ReadingCodeStatus;
use App\Models\RptReadingCode;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class CustomerController extends Controller
{
    /**
     * Display a listing of customers.
     */
  
    public function index(Request $request): JsonResponse
    {
        try {
            $companyId = $request->query('company_id');
            $propId = $request->query('propid');

            // Validate required parameters
            if (!$companyId) {
                return response()->json([
                    'success' => false,
                    'message' => 'company_id parameter is required',
                    'data' => []
                ], 400);
            }

            if (!$propId) {
                return response()->json([
                    'success' => false,
                    'message' => 'propid parameter is required',
                    'data' => []
                ], 400);
            }

            // Validate that company exists
            $company = Company::where('CompanyID', $companyId)->first();
            if (!$company) {
                return response()->json([
                    'success' => false,
                    'message' => 'Company not found',
                    'data' => []
                ], 404);
            }

            // Validate that property exists
            $property = Property::where('PropID', $propId)->first();
            if (!$property) {
                return response()->json([
                    'success' => false,
                    'message' => 'Property not found',
                    'data' => []
                ], 404);
            }

            // Build query with filters
            $query = TmpMeterReading::where('CompanyID', $companyId)
                ->whereHas('unit', function($q) use ($propId) {
                    $q->where('PropID', $propId);
                })
                ->with(['customer', 'unit.property']);

            $customers = $query->orderBy('tmp_meterreading.CustomerID', 'asc')
                ->get();

            $formattedCustomers = $customers->map(function ($meterReading) use ($company) {
                $customer = $meterReading->customer;
                if (!$customer) return null;

                // Get all customer fields and exclude specified ones
                $customerData = $customer->toArray();
                $excludeFields = [
                    'WInitialReading', 'EInitialReading', 'WAvgCons', 'EAvgCons',
                    'AccountBalance', 'TotalDebit', 'TotalCredit', 'AccountType',
                    'ContractDate', 'Deposit', 'DepositDate'
                ];
                $customerData = array_diff_key($customerData, array_flip($excludeFields));

                return array_merge($customerData, [
                    'PropID' => $meterReading->unit ? $meterReading->unit->PropID : null,
                    'PropName' => $meterReading->unit && $meterReading->unit->property ? $meterReading->unit->property->PropName : null,
                    'CompanyName' => $company ? $company->CompanyName : null,
                    'UnitIdentity' => $meterReading->unit ? $meterReading->unit->UnitIdentity : null,
                    // 'meter_reading' => [
                        'id' => $meterReading->MeterReadingID,
                        'billing_period' => $meterReading->BillingPeriod,
                        'consumption_type' => $meterReading->ConsType,
                        'customer_id' => $meterReading->CustomerID,
                        'unit_id' => $meterReading->UnitID,
                        'meter_no' => $meterReading->MeterNo,
                        'reading' => $meterReading->Reading,
                        'reading_date' => $meterReading->ReadingDate,
                        'consumption' => $meterReading->Consumption,
                        'base_of_billing' => $meterReading->BaseOfBilling,
                        'reading_comments' => $meterReading->ReadingComments,
                        'previous_reading' => $meterReading->PrvReading,
                        'previous_reading_date' => $meterReading->PrvReadingDate,
                        'previous_reading_id' => $meterReading->PrvReadingID,
                        'image_path' => $meterReading->ImagePath,
                        'company_id' => $meterReading->CompanyID
                    // ]
                    
                ]);
            })->filter(); // Remove null entries

            return response()->json(
              $formattedCustomers
               
            );

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

    /**
     * Get reading code statuses.
     */
    public function getReadingCodeStatuses(): JsonResponse
    {
        try {
            $data = ReadingCodeStatus::all();

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

    /**
     * Get RPT reading codes.
     */
    public function getRptReadingCodes(): JsonResponse
    {
        try {
            $data = RptReadingCode::all();

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