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

/**
 * Property Management Class
 * Handles property CRUD operations and property-related queries
 */
class Property extends BaseModel {
    protected $tableName = 'properties';
    protected $tenantColumn = 'owner_id'; // Multi-tenant isolation by owner
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Create a new property
     */
    public function createProperty($data) {
        // Validate required fields
        $required = ['owner_id', 'name', 'type', 'location_area'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new Exception("Field {$field} is required");
            }
        }
        
        $propertyData = [
            'owner_id' => $data['owner_id'],
            'manager_id' => $data['manager_id'] ?? null,
            'name' => $data['name'],
            'type' => $data['type'],
            'location_area' => $data['location_area'],
            'street_address' => $data['street_address'] ?? null,
            'city' => $data['city'] ?? null,
            'geo_lat' => $data['geo_lat'] ?? null,
            'geo_lng' => $data['geo_lng'] ?? null,
            'l_r_number' => $data['l_r_number'] ?? null,
            'land_size' => $data['land_size'] ?? null,
            'total_floors' => $data['total_floors'] ?? 1,
            'total_units' => $data['total_units'] ?? 0,
            'construction_year' => $data['construction_year'] ?? null,
            'description' => $data['description'] ?? null,
            'management_fee_percentage' => $data['management_fee_percentage'] ?? 0.00,
            'vat_enabled' => $data['vat_enabled'] ?? false,
            'cover_image_url' => $data['cover_image_url'] ?? null
        ];
        
        $propertyId = $this->create($propertyData);
        
        // Add amenities if provided
        if (!empty($data['amenities']) && is_array($data['amenities'])) {
            $this->addAmenities($propertyId, $data['amenities']);
        }
        
        return $propertyId;
    }
    
    /**
     * Update property
     */
    public function updateProperty($id, $data, $ownerId) {
        return $this->update($id, $data, $ownerId);
    }
    
    /**
     * Get property with units and amenities
     */
    public function getPropertyDetails($id, $ownerId = null) {
        $property = $this->getById($id, $ownerId);
        
        if (!$property) {
            return null;
        }
        
        // Get units
        $unitModel = new Unit();
        $property['units'] = $unitModel->getUnitsByProperty($id);
        
        // Get amenities
        $property['amenities'] = $this->getAmenities($id);
        
        // Get owner details
        $sql = "SELECT id, first_name, last_name, email, phone FROM users WHERE id = ?";
        $result = $this->db->query($sql, [$property['owner_id']]);
        $property['owner'] = $result->fetch_assoc();
        
        // Get manager details if assigned
        if ($property['manager_id']) {
            $result = $this->db->query($sql, [$property['manager_id']]);
            $property['manager'] = $result->fetch_assoc();
        }
        
        return $property;
    }
    
    /**
     * Get all properties for an owner
     */
    public function getPropertiesByOwner($ownerId, $filters = []) {
        return $this->getAll($filters, $ownerId);
    }
    
    /**
     * Add amenities to property
     */
    public function addAmenities($propertyId, $amenityIds) {
        foreach ($amenityIds as $amenityId) {
            $sql = "INSERT IGNORE INTO property_amenities (property_id, amenity_id) VALUES (?, ?)";
            $this->db->execute($sql, [$propertyId, $amenityId]);
        }
    }
    
    /**
     * Get amenities for a property
     */
    public function getAmenities($propertyId) {
        $sql = "SELECT a.* FROM amenities a 
                INNER JOIN property_amenities pa ON a.id = pa.amenity_id 
                WHERE pa.property_id = ?";
        
        $result = $this->db->query($sql, [$propertyId]);
        $amenities = [];
        
        while ($row = $result->fetch_assoc()) {
            $amenities[] = $row;
        }
        
        return $amenities;
    }
    
    /**
     * Remove amenity from property
     */
    public function removeAmenity($propertyId, $amenityId) {
        $sql = "DELETE FROM property_amenities WHERE property_id = ? AND amenity_id = ?";
        return $this->db->execute($sql, [$propertyId, $amenityId]);
    }
    
    /**
     * Get property statistics
     */
    public function getPropertyStats($propertyId, $ownerId = null) {
        $property = $this->getById($propertyId, $ownerId);
        
        if (!$property) {
            return null;
        }
        
        // Get unit statistics
        $sql = "SELECT 
                    COUNT(*) as total_units,
                    SUM(CASE WHEN status = 'occupied' THEN 1 ELSE 0 END) as occupied_units,
                    SUM(CASE WHEN status = 'vacant' THEN 1 ELSE 0 END) as vacant_units,
                    SUM(CASE WHEN is_for_sale = 1 THEN 1 ELSE 0 END) as units_for_sale,
                    SUM(CASE WHEN status = 'sold' THEN 1 ELSE 0 END) as sold_units
                FROM units 
                WHERE property_id = ?";
        
        $result = $this->db->query($sql, [$propertyId]);
        $stats = $result->fetch_assoc();
        
        // Get financial statistics
        $sql = "SELECT 
                    SUM(CASE WHEN status = 'paid' THEN total_amount ELSE 0 END) as total_collected,
                    SUM(CASE WHEN status IN ('unpaid', 'overdue') THEN balance ELSE 0 END) as total_outstanding
                FROM invoices 
                WHERE property_id = ?";
        
        $result = $this->db->query($sql, [$propertyId]);
        $financialStats = $result->fetch_assoc();
        
        return array_merge($stats, $financialStats);
    }
}
?>
