<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class BuildingController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager']);
    }

    public function index(): void
    {
        $buildings = $this->db->fetchAll("SELECT b.*, p.name AS property_name, COUNT(u.id) AS unit_count FROM buildings b JOIN properties p ON p.id=b.property_id LEFT JOIN units u ON u.building_id=b.id GROUP BY b.id ORDER BY p.name, b.name");
        $properties = $this->db->fetchAll("SELECT id,name FROM properties WHERE status='active' ORDER BY name");
        $this->adminView('building.index', compact('buildings','properties') + ['title'=>'Buildings']);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $this->db->insert('buildings', [
            'property_id' => (int)$this->input('property_id'),
            'name'        => Helper::sanitize($this->input('name','')),
            'code'        => strtoupper(Helper::sanitize($this->input('code',''))) ?: null,
            'floors'      => (int)$this->input('floors',1),
            'description' => $this->input('description','') ?: null,
            'status'      => 'active',
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);
        Helper::setFlash('success','Building added.');
        $this->redirect(APP_URL.'/admin/buildings');
    }

    public function edit(string $id): void
    {
        $building   = $this->db->fetch("SELECT * FROM buildings WHERE id=?", [$id]);
        $properties = $this->db->fetchAll("SELECT id,name FROM properties WHERE status='active' ORDER BY name");
        $this->adminView('building.edit', compact('building','properties') + ['title'=>'Edit Building']);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('buildings', [
            'property_id' => (int)$this->input('property_id'),
            'name'        => Helper::sanitize($this->input('name','')),
            'floors'      => (int)$this->input('floors',1),
            'status'      => $this->input('status','active'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id=?', [$id]);
        Helper::setFlash('success','Building updated.');
        $this->redirect(APP_URL.'/admin/buildings');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('buildings', ['status'=>'inactive','updated_at'=>date('Y-m-d H:i:s')], 'id=?', [$id]);
        Helper::setFlash('success','Building removed.');
        $this->redirect(APP_URL.'/admin/buildings');
    }
}
