<?php
namespace App\Controllers;

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

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

    public function index(): void
    {
        $propId = $_GET['property_id'] ?? '';
        $status = $_GET['status'] ?? '';
        $conditions = ['1=1']; $params = [];
        if ($propId) { $conditions[]='u.property_id=?'; $params[]=$propId; }
        if ($status) { $conditions[]='u.status=?'; $params[]=$status; }
        $where = implode(' AND ',$conditions);
        $units = $this->db->fetchAll(
            "SELECT u.*, b.name AS building_name, p.name AS property_name,
                    CONCAT(t.first_name,' ',t.last_name) AS current_tenant
             FROM units u
             JOIN buildings b ON b.id=u.building_id
             JOIN properties p ON p.id=u.property_id
             LEFT JOIN leases l ON l.unit_id=u.id AND l.status='active'
             LEFT JOIN tenants t ON t.id=l.tenant_id
             WHERE $where ORDER BY p.name, b.name, u.unit_number", $params
        );
        $properties = $this->db->fetchAll("SELECT id,name FROM properties WHERE status='active' ORDER BY name");
        $buildings  = $this->db->fetchAll("SELECT id,name,property_id FROM buildings WHERE status='active' ORDER BY name");
        $this->adminView('unit.index', compact('units','properties','buildings','propId','status') + ['title'=>'Units & Rooms']);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $building = $this->db->fetch("SELECT property_id FROM buildings WHERE id=?", [$this->input('building_id')]);
        $unitNum = Helper::sanitize($this->input('unit_number',''));
        $code = 'ZBR-'.str_pad((int)$this->db->fetchColumn("SELECT COUNT(*)+1 FROM units"), 6,'0',STR_PAD_LEFT);
        $this->db->insert('units', [
            'building_id'      => (int)$this->input('building_id'),
            'property_id'      => $building['property_id'] ?? 0,
            'unit_number'      => $unitNum,
            'unit_code'        => $code,
            'floor'            => (int)$this->input('floor',1),
            'unit_type'        => $this->input('unit_type','apartment'),
            'bedrooms'         => (int)$this->input('bedrooms',1),
            'bathrooms'        => (int)$this->input('bathrooms',1),
            'floor_size'       => $this->input('floor_size') ?: null,
            'rent_period'      => $this->input('rent_period','monthly'),
            'daily_rent'       => $this->input('daily_rent') ? (float)$this->input('daily_rent') : null,
            'weekly_rent'      => $this->input('weekly_rent') ? (float)$this->input('weekly_rent') : null,
            'monthly_rent'     => (float)$this->input('monthly_rent',0),
            'annual_rent'      => $this->input('annual_rent') ?: null,
            'security_deposit' => $this->input('security_deposit') ?: null,
            'is_furnished'     => $this->input('is_furnished') ? 1 : 0,
            'has_parking'      => $this->input('has_parking') ? 1 : 0,
            'has_wifi'         => $this->input('has_wifi') ? 1 : 0,
            'has_ac'           => $this->input('has_ac') ? 1 : 0,
            'has_water'        => 1,
            'has_electricity'  => 1,
            'pets_allowed'     => $this->input('pets_allowed') ? 1 : 0,
            'description'      => $this->input('description','') ?: null,
            'status'           => 'available',
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s'),
        ]);
        Helper::setFlash('success','Unit added successfully.');
        $this->redirect(APP_URL.'/admin/units');
    }

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

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('units', [
            'building_id'    => (int)$this->input('building_id'),
            'unit_number'    => Helper::sanitize($this->input('unit_number','')),
            'floor'          => (int)$this->input('floor',1),
            'unit_type'      => $this->input('unit_type','apartment'),
            'bedrooms'       => (int)$this->input('bedrooms',1),
            'bathrooms'      => (int)$this->input('bathrooms',1),
            'floor_size'     => $this->input('floor_size') ?: null,
            'rent_period'    => $this->input('rent_period','monthly'),
            'daily_rent'     => $this->input('daily_rent') ? (float)$this->input('daily_rent') : null,
            'weekly_rent'    => $this->input('weekly_rent') ? (float)$this->input('weekly_rent') : null,
            'monthly_rent'   => (float)$this->input('monthly_rent',0),
            'security_deposit'=> $this->input('security_deposit') ?: null,
            'is_furnished'   => $this->input('is_furnished') ? 1 : 0,
            'has_parking'    => $this->input('has_parking') ? 1 : 0,
            'has_wifi'       => $this->input('has_wifi') ? 1 : 0,
            'has_ac'         => $this->input('has_ac') ? 1 : 0,
            'pets_allowed'   => $this->input('pets_allowed') ? 1 : 0,
            'status'         => $this->input('status','available'),
            'description'    => $this->input('description','') ?: null,
            'updated_at'     => date('Y-m-d H:i:s'),
        ], 'id=?', [$id]);
        Helper::setFlash('success','Unit updated.');
        $this->redirect(APP_URL.'/admin/units');
    }

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