<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MeterReading;
use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; 


class MeterReadingController extends Controller
{

    public function index()
    {
        $readings = MeterReading::with('user')
                                ->orderBy('created_at', 'desc')
                                ->paginate(10);

        return response()->json($readings);
    }

    public function store(Request $request)
    {
       
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $reading = MeterReading::with('user')->findOrFail($id);
        return response()->json($reading);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
{
    $reading = MeterReading::findOrFail($id);

    $validatedData = $request->validate([
        'meter_value' => 'nullable|numeric|min:0',
        'status'      => 'required|in:verified,rejected,pending',
        'admin_note'  => 'nullable|string',
    ]);

    // DEFINISIKAN VARIABEL STATUS
    $status = $validatedData['status'];
    $meterValue = $validatedData['meter_value'] ?? $reading->meter_value;

    // UPDATE DATABASE
    $reading->update([
        'meter_value' => $meterValue,
        'admin_note'  => $validatedData['admin_note'],
        'status'      => $status,
    ]);

    // 1. LOGIKA NOTIFIKASI REJECTED
    if ($status == 'rejected') {
        $user = \App\Models\User::find($reading->user_id);
        if ($user) {
            $user->notify(new \App\Notifications\MeterRejectedNotification($reading));
        }
    }

    // 2. LOGIKA INVOICE VERIFIED
    $invoiceExists = Invoice::where('meter_reading_id', $reading->id)->exists();

    if ($status == 'verified' && !$invoiceExists) {
        try {
            $harga_per_m3 = 2500;
            $biaya_admin = 2000;

            $periode = \Carbon\Carbon::create($reading->year, $reading->month, 1);
            $periode_lalu = (clone $periode)->subMonth();
            
            $meteran_lalu = MeterReading::where('user_id', $reading->user_id)
                ->where('month', $periode_lalu->month)
                ->where('year', $periode_lalu->year)
                ->where('status', 'verified')
                ->first();

            $angka_lalu = $meteran_lalu ? $meteran_lalu->meter_value : 0;
            $pemakaian = $meterValue - $angka_lalu;
            if ($pemakaian < 0) $pemakaian = $meterValue; 

            Invoice::create([
                'user_id' => $reading->user_id,
                'meter_reading_id' => $reading->id,
                'invoice_number' => 'INV-' . $reading->id . '-' . time(),           
                'total_amount' => ($pemakaian * $harga_per_m3) + $biaya_admin,
                'due_date' => \Carbon\Carbon::create($reading->year, $reading->month, 20),
                'status' => 'unpaid',
            ]);
        } catch (\Exception $e) {
            \Log::error("Gagal buat invoice: " . $e->getMessage());
        }
    }

    return response()->json($reading->load('user'));
}
   
}
