<?php
require_once __DIR__ . '/BaseModel.php';

/**
 * Unit Management Class
 * Handles unit CRUD operations and unit-related queries
 */
class Unit extends BaseModel {
    protected $tableName = 'units';
    protected $tenantColumn = null; // Units are isolated by property_id, which is handled separately
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Create a new unit
     */
    public function createUnit($data) {
        // Validate required fields
        $required = ['property_id', 'unit_number', 'rent_amount'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new Exception("Field {$field} is required");
            }
        }
        
        $unitData = [
            'property_id' => $data['property_id'],
            'unit_type_id' => $data['unit_type_id'] ?? null,
            'unit_number' => $data['unit_number'],
            'floor_level' => $data['floor_level'] ?? null,
            'size_sqm' => $data['size_sqm'] ?? null,
            'bedrooms' => $data['bedrooms'] ?? 0,
            'bathrooms' => $data['bathrooms'] ?? 0,
            'balconies' => $data['balconies'] ?? 0,
            'furnishing' => $data['furnishing'] ?? 'Unfurnished',
            'has_parking' => $data['has_parking'] ?? false,
            'parking_slot_no' => $data['parking_slot_no'] ?? null,
            'electricity_meter_no' => $data['electricity_meter_no'] ?? null,
            'water_meter_no' => $data['water_meter_no'] ?? null,
            'rent_amount' => $data['rent_amount'],
            'deposit_amount' => $data['deposit_amount'] ?? 0.00,
            'sale_price' => $data['sale_price'] ?? null,
            'status' => $data['status'] ?? 'vacant',
            'is_for_sale' => $data['is_for_sale'] ?? false,
            'notes' => $data['notes'] ?? null
        ];
        
        $unitId = $this->create($unitData);
        
        // Update property total_units count
        $this->updatePropertyUnitCount($data['property_id']);
        
        return $unitId;
    }
    
    /**
     * Update unit
     */
    public function updateUnit($id, $data) {
        return $this->update($id, $data);
    }
    
    /**
     * Get unit with property and lease details
     */
    public function getUnitDetails($id) {
        $unit = $this->getById($id);
        
        if (!$unit) {
            return null;
        }
        
        // Get property details
        $propertyModel = new Property();
        $unit['property'] = $propertyModel->getById($unit['property_id']);
        
        // Get active lease if exists
        $sql = "SELECT * FROM leases WHERE unit_id = ? AND status = 'active' ORDER BY start_date DESC LIMIT 1";
        $result = $this->db->query($sql, [$id]);
        $unit['active_lease'] = $result->fetch_assoc();
        
        // Get tenant if lease exists
        if ($unit['active_lease']) {
            $sql = "SELECT id, first_name, last_name, email, phone FROM users WHERE id = ?";
            $result = $this->db->query($sql, [$unit['active_lease']['tenant_id']]);
            $unit['tenant'] = $result->fetch_assoc();
        }
        
        // Get unit type if exists
        if ($unit['unit_type_id']) {
            $sql = "SELECT * FROM unit_types WHERE id = ?";
            $result = $this->db->query($sql, [$unit['unit_type_id']]);
            $unit['unit_type'] = $result->fetch_assoc();
        }
        
        return $unit;
    }
    
    /**
     * Get all units for a property
     */
    public function getUnitsByProperty($propertyId, $filters = []) {
        $sql = "SELECT * FROM {$this->tableName} WHERE property_id = ?";
        $params = [$propertyId];
        
        foreach ($filters as $column => $value) {
            $sql .= " AND {$column} = ?";
            $params[] = $value;
        }
        
        $sql .= " ORDER BY floor_level DESC, unit_number ASC";
        
        $result = $this->db->query($sql, $params);
        $units = [];
        
        while ($row = $result->fetch_assoc()) {
            $units[] = $row;
        }
        
        return $units;
    }
    
    /**
     * Get available units (vacant)
     */
    public function getAvailableUnits($propertyId = null) {
        $sql = "SELECT u.*, p.name as property_name, p.location_area 
                FROM units u 
                INNER JOIN properties p ON u.property_id = p.id 
                WHERE u.status = 'vacant'";
        
        $params = [];
        if ($propertyId) {
            $sql .= " AND u.property_id = ?";
            $params[] = $propertyId;
        }
        
        $sql .= " ORDER BY p.name, u.unit_number";
        
        $result = $this->db->query($sql, $params);
        $units = [];
        
        while ($row = $result->fetch_assoc()) {
            $units[] = $row;
        }
        
        return $units;
    }
    
    /**
     * Get units for sale
     */
    public function getUnitsForSale($propertyId = null) {
        $sql = "SELECT u.*, p.name as property_name, p.location_area 
                FROM units u 
                INNER JOIN properties p ON u.property_id = p.id 
                WHERE u.is_for_sale = 1 AND u.status != 'sold'";
        
        $params = [];
        if ($propertyId) {
            $sql .= " AND u.property_id = ?";
            $params[] = $propertyId;
        }
        
        $sql .= " ORDER BY p.name, u.unit_number";
        
        $result = $this->db->query($sql, $params);
        $units = [];
        
        while ($row = $result->fetch_assoc()) {
            $units[] = $row;
        }
        
        return $units;
    }
    
    /**
     * Update property unit count
     */
    private function updatePropertyUnitCount($propertyId) {
        $sql = "UPDATE properties SET total_units = (SELECT COUNT(*) FROM units WHERE property_id = ?) WHERE id = ?";
        $this->db->execute($sql, [$propertyId, $propertyId]);
    }
    
    /**
     * Mark unit as sold
     */
    public function markAsSold($unitId) {
        return $this->update($unitId, [
            'status' => 'sold',
            'is_for_sale' => false
        ]);
    }
}
?>
