<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\MeterReading;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class MeterReadingController extends Controller
{
    public function create()
    {
        // 1. Cek apakah admin membuka akses upload
        $isOpen = DB::table('app_settings')->where('key', 'is_upload_open')->value('value');
        if (!$isOpen) { 
            return view('meter.closed'); 
        }

        $user = Auth::user();
        $currentMonth = (int) Carbon::now()->month;
        $currentYear = (int) Carbon::now()->year;

        // 2. Cari data untuk periode bulan & tahun ini
        $existingReading = MeterReading::where('user_id', $user->id)
            ->where('month', $currentMonth)
            ->where('year', $currentYear)
            ->first();

        // 3. LOGIKA REDIRECT:
        // Jika sudah ada data dan statusnya BUKAN rejected (artinya pending/verified),
        // warga tidak boleh upload lagi, arahkan ke halaman status.
        if ($existingReading && $existingReading->status !== 'rejected') {
            return view('meter.uploaded', ['reading' => $existingReading]);
        }
        
        // 4. Jika data belum ada ATAU statusnya rejected, tampilkan form upload.
        return view('meter.create', ['oldReading' => $existingReading]);
    }

    public function store(Request $request)
    {
        // 1. Cek Saklar Admin
        $isOpen = DB::table('app_settings')->where('key', 'is_upload_open')->value('value');
        if (!$isOpen) {
            return redirect()->back()->with('error', 'Akses upload sedang ditutup oleh admin.');
        }

        // 2. Validasi File
        $request->validate([
            'meter_image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $user = Auth::user();
        $currentMonth = (int) Carbon::now()->month;
        $currentYear = (int) Carbon::now()->year;

        // 3. Keamanan Tambahan: Cek lagi status di database
        $existing = MeterReading::where('user_id', $user->id)
            ->where('month', $currentMonth)
            ->where('year', $currentYear)
            ->first();

        if ($existing && $existing->status !== 'rejected') {
            return redirect()->back()->with('error', 'Pencatatan sedang diproses atau sudah selesai.');
        }

        if ($request->hasFile('meter_image')) {
            // A. Siapkan Nama & Simpan File ke Storage
            $image = $request->file('meter_image');
            $imageName = $user->id . '_' . time() . '.' . $image->extension();
            
            // Simpan ke: storage/app/public/meter-images/
            $image->storeAs('meter-images', $imageName, 'public');

            // B. Hapus foto lama jika ini adalah upload ulang (opsional tapi bagus agar storage tidak penuh)
            if ($existing && $existing->image_path) {
                Storage::disk('public')->delete('meter-images/' . $existing->image_path);
            }

            // C. LOGIKA ANTI-DUPLIKASI: updateOrCreate
            // Cari berdasarkan user_id, month, year. 
            // Kalau ketemu (meskipun statusnya rejected), dia cuma UPDATE baris tersebut.
            MeterReading::updateOrCreate(
                [
                    'user_id' => $user->id,
                    'month'   => $currentMonth,
                    'year'    => $currentYear,
                ],
                [
                    'image_path' => $imageName,
                    'status'     => 'pending', // Reset status ke pending agar Admin cek lagi
                    'admin_note' => null,      // Hapus catatan reject yang lama
                    'meter_value'=> null,      // Kosongkan angka meter agar Admin isi ulang dari foto baru
                ]
            );

            return redirect()->route('meter.create')->with('success', 'Foto meteran berhasil dikirim!');
        }

        return redirect()->back()->with('error', 'Gagal memproses gambar.');
    }
}