<?php

namespace App\Http\Controllers;

use App\Models\Property;
use App\Models\ProUnit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UnitController extends Controller
{
    public function index(Property $property, Request $request)
    {
        $status = $request->input('status');
        
        $units = $property->units()
            ->when($status, function($query) use ($status) {
                return $query->where('OccupationStatus', $status);
            })
            ->orderByRaw("FIELD(OccupationStatus, 'InActive', 'Active', 'Under')")
            ->paginate(10)
            ->appends(['status' => $status]);
            
        return view('units.index', [
            'property' => $property, 
            'units' => $units,
            'currentStatus' => $status
        ]);
    }

    public function create(Property $property)
    {
        return view('units.create', compact('property'));
    }

    public function store(Request $request, Property $property)
    {
        $validated = $request->validate([
            'UnitIdentity' => 'required|string|max:20',
            'BlockNo' => 'nullable|string|max:20',
            'FloorNo' => 'nullable|string|max:20',
            'DoorNo' => 'nullable|string|max:20',
            'UnitDesc' => 'nullable|string|max:100',
            'EFixedCharge' => 'required|numeric|min:0',
            'WFixedCharge' => 'required|numeric|min:0',
            'MonthlyRent' => 'required|numeric|min:0',
            'WMeterNo' => 'nullable|string|max:20',
            'EMeterNo' => 'nullable|string|max:20',
            'WLastReading' => 'required|integer|min:0',
            'ELastReading' => 'required|integer|min:0',
            'WMaxReading' => 'required|integer|min:0',
            'EMaxReading' => 'required|integer|min:0',
            'OccupationStatus' => 'required|string|in:Vacant,Occupied,Under Maintenance'
        ]);

        try {
            DB::beginTransaction();
            
            $property->units()->create($validated);
            
            DB::commit();
            
            return redirect()->route('properties.units.index', $property->PropID)
                ->with('success', 'Unit created successfully.');
                
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Error creating unit: ' . $e->getMessage());
        }
    }

    public function show(Property $property, ProUnit $unit)
    {
        return view('units.show', compact('property', 'unit'));
    }

    public function edit(Property $property, ProUnit $unit)
    {
        return view('units.edit', compact('property', 'unit'));
    }

    public function update(Request $request, Property $property, ProUnit $unit)
    {
        $validated = $request->validate([
            'UnitIdentity' => 'required|string|max:20',
            'BlockNo' => 'nullable|string|max:20',
            'FloorNo' => 'nullable|string|max:20',
            'DoorNo' => 'nullable|string|max:20',
            'UnitDesc' => 'nullable|string|max:100',
            'EFixedCharge' => 'required|numeric|min:0',
            'WFixedCharge' => 'required|numeric|min:0',
            'MonthlyRent' => 'required|numeric|min:0',
            'WMeterNo' => 'nullable|string|max:20',
            'EMeterNo' => 'nullable|string|max:20',
            'WLastReading' => 'required|integer|min:0',
            'ELastReading' => 'required|integer|min:0',
            'WMaxReading' => 'required|integer|min:0',
            'EMaxReading' => 'required|integer|min:0',
            'UnitActive' => 'required|boolean',
        ]);

        try {
            DB::beginTransaction();
            
            // Set OccupationStatus based on UnitActive
            $validated['OccupationStatus'] = $validated['UnitActive'] ? 'InActive' : 'Under';
            
            $unit->update($validated);
            
            DB::commit();
            
            return redirect()->route('properties.units.index', $property->PropID)
                ->with('success', 'Unit updated successfully.');
                
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Error updating unit: ' . $e->getMessage());
        }
    }

    public function destroy(Property $property, ProUnit $unit)
    {
        try {
            $unit->delete();
            return redirect()->route('properties.units.index', $property->PropID)
                ->with('success', 'Unit deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', 'Error deleting unit: ' . $e->getMessage());
        }
    }
}
