<?php
namespace App\Controllers;

use App\Models\ApartmentModel;
use CodeIgniter\Controller;

class Apartment extends Controller
{
    public function index()
    {
        $model = new ApartmentModel();
        $data['apartments'] = $model->orderBy('id', 'DESC')->findAll();
        return view('apartmentList', $data);
    }

    public function add()
    {
        return view('apartmentAdd');
    }

    public function save()
    {
        $model = new ApartmentModel();

        $data = [
            'apartName'    => $this->request->getPost('apartName'),
            'apartAddress' => $this->request->getPost('apartAddress'), // corrected
            'createdby'    => $this->request->getPost('createdby'),
        ];

        if ($model->insert($data)) {
            return redirect()->to('/apartment')->with('success', 'Apartment added successfully!');
        } else {
            return redirect()->back()->with('error', 'Failed to add apartment.');
        }
    }

    public function edit($id)
    {
        $model = new ApartmentModel();
        $data['apartment'] = $model->find($id);
        return view('apartmentEdit', $data);
    }

    public function update($id)
    {
        $model = new ApartmentModel();

        $data = [
            'apartName'    => $this->request->getPost('apartName'),
            'apartAddress' => $this->request->getPost('apartAddress'), // corrected
            'createdby'    => $this->request->getPost('createdby'),
        ];

        $model->update($id, $data);
        return redirect()->to('/apartment')->with('success', 'Apartment updated successfully!');
    }

    public function delete($id)
    {
        $model = new ApartmentModel();
        $model->delete($id);
        return redirect()->to('/apartment')->with('success', 'Apartment deleted successfully!');
    }
}
