<?php

namespace App\Http\Controllers;

use App\Models\MeterReader;
use App\Models\Property;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class MeterReaderController extends Controller
{
    /**
     * Display a listing of meter readers.
     */
    public function index()
    {
        $companyId = $this->user()->CompanyID;

        if (!$companyId) {
            return redirect()->back()->with('error', 'Your account is not associated with any company.');
        }

        $meterReaders = MeterReader::where('company_id', $companyId)
            ->with(['property', 'company'])
            ->orderBy('first_name')
            ->orderBy('last_name')
            ->paginate(15);

        return view('meter-readers.index', compact('meterReaders'));
    }

    /**
     * Show the form for creating a new meter reader.
     */
    public function create()
    {
        $companyId = $this->user()->CompanyID;

        if (!$companyId) {
            return redirect()->back()->with('error', 'Your account is not associated with any company.');
        }

        $properties = Property::where('CompanyID', $companyId)
            ->orderBy('PropName')
            ->get();

        return view('meter-readers.create', compact('properties'));
    }

    /**
     * Store a newly created meter reader in storage.
     */
    public function store(Request $request)
    {
        $companyId = $this->user()->CompanyID;

        if (!$companyId) {
            return redirect()->back()->with('error', 'Your account is not associated with any company.');
        }

        $request->validate([
            'username' => [
                'required',
                'string',
                'max:50',
                Rule::unique('meter_readers')
            ],
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => [
                'required',
                'string',
                'email',
                'max:100',
                Rule::unique('meter_readers')
            ],
            'phone_number' => 'required|string|max:20',
            'password' => 'required|string|min:8|confirmed',
            'property_id' => 'nullable|exists:property,PropID',
        ]);

        $meterReader = new MeterReader([
            'username' => $request->username,
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone_number' => $request->phone_number,
            'password' => Hash::make($request->password),
            'company_id' => $companyId,
            'PropID' => $request->property_id,
        ]);

        $meterReader->save();

        return redirect()->route('meter-readers.index')
            ->with('success', 'Meter reader created successfully.');
    }

    /**
     * Display the specified meter reader.
     */
    public function show(MeterReader $meterReader)
    {
        // Check if meter reader belongs to user's company
        if ($meterReader->company_id !== $this->user()->CompanyID) {
            abort(403, 'Unauthorized');
        }

        $meterReader->load(['property', 'company']);

        return view('meter-readers.show', compact('meterReader'));
    }

    /**
     * Show the form for editing the specified meter reader.
     */
    public function edit(MeterReader $meterReader)
    {
        // Check if meter reader belongs to user's company
        if ($meterReader->company_id !== $this->user()->CompanyID) {
            abort(403, 'Unauthorized');
        }

        $properties = Property::where('CompanyID', $this->user()->CompanyID)
            ->orderBy('PropName')
            ->get();

        return view('meter-readers.edit', compact('meterReader', 'properties'));
    }

    /**
     * Update the specified meter reader in storage.
     */
    public function update(Request $request, MeterReader $meterReader)
    {
        // Check if meter reader belongs to user's company
        if ($meterReader->company_id !== $this->user()->CompanyID) {
            abort(403, 'Unauthorized');
        }

        $request->validate([
            'username' => [
                'required',
                'string',
                'max:50',
                Rule::unique('meter_readers')->ignore($meterReader->id)
            ],
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => [
                'required',
                'string',
                'email',
                'max:100',
                Rule::unique('meter_readers')->ignore($meterReader->id)
            ],
            'phone_number' => 'required|string|max:20',
            'password' => 'nullable|string|min:8|confirmed',
            'property_id' => 'nullable|exists:property,PropID',
        ]);

        $meterReader->username = $request->username;
        $meterReader->first_name = $request->first_name;
        $meterReader->last_name = $request->last_name;
        $meterReader->email = $request->email;
        $meterReader->phone_number = $request->phone_number;
        $meterReader->PropID = $request->property_id;

        if ($request->filled('password')) {
            $meterReader->password = Hash::make($request->password);
        }

        $meterReader->save();

        return redirect()->route('meter-readers.index')
            ->with('success', 'Meter reader updated successfully.');
    }

    /**
     * Remove the specified meter reader from storage.
     */
    public function destroy(MeterReader $meterReader)
    {
        // Check if meter reader belongs to user's company
        if ($meterReader->company_id !== $this->user()->CompanyID) {
            abort(403, 'Unauthorized');
        }

        $meterReader->delete();

        return redirect()->route('meter-readers.index')
            ->with('success', 'Meter reader deleted successfully.');
    }
}
