<?php
class PropertyModel {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    // Filtreli İlan Çekme
    public function getFiltered($filters = []) {
        $sql = "SELECT * FROM properties WHERE status = 'approved'";
        $params = [];

        if (!empty($filters['category'])) {
             $sql .= " AND category = :category";
             $params['category'] = $filters['category'];
        }

        if (!empty($filters['type'])) {
            $sql .= " AND type = :type";
            $params['type'] = $filters['type'];
        }

        if (!empty($filters['location'])) {
            $sql .= " AND location LIKE :location";
            $params['location'] = '%' . $filters['location'] . '%';
        }

        if (!empty($filters['min_price'])) {
            $sql .= " AND price >= :min_price";
            $params['min_price'] = $filters['min_price'];
        }

        if (!empty($filters['max_price'])) {
            $sql .= " AND price <= :max_price";
            $params['max_price'] = $filters['max_price'];
        }

        $sql .= " ORDER BY created_at DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    // Tekil İlan Getir (Slug ile)
    public function getPropertyBySlug($slug) {
        // İlan ve Danışman bilgilerini çek
        // NOT: Eğer users tablosunda 'image' sütunu yoksa burası hata verir.
        $sql = "SELECT p.*, 
                       u.name as agent_name, 
                       u.phone as agent_phone, 
                       u.email as agent_email,
                       u.image as agent_image 
                FROM properties p 
                LEFT JOIN users u ON p.user_id = u.id 
                WHERE p.slug = :slug AND p.status = 'approved' LIMIT 1";
                
        $stmt = $this->db->prepare($sql);
        $stmt->execute(['slug' => $slug]);
        $property = $stmt->fetch(PDO::FETCH_OBJ);

        // Eğer ilan bulunduysa resimleri de çek
        if ($property) {
            // property_images tablosunun varlığından emin olmalısın
            $stmtImg = $this->db->prepare("SELECT * FROM property_images WHERE property_id = :id ORDER BY is_cover DESC");
            $stmtImg->execute(['id' => $property->id]);
            $property->images = $stmtImg->fetchAll(PDO::FETCH_OBJ);
        }

        return $property;
    }

    // İlan görüntülenme kaydı (aynı oturumda bir kez sayılır)
    public function recordView($property_id, $session_id) {
        $check = $this->db->prepare("SELECT id FROM property_views WHERE property_id = :property_id AND session_id = :session_id LIMIT 1");
        $check->execute([
            'property_id' => $property_id,
            'session_id' => $session_id
        ]);

        if ($check->fetch(PDO::FETCH_OBJ)) {
            return false;
        }

        $insert = $this->db->prepare("INSERT INTO property_views (property_id, session_id) VALUES (:property_id, :session_id)");
        $insert->execute([
            'property_id' => $property_id,
            'session_id' => $session_id
        ]);

        $update = $this->db->prepare("UPDATE properties SET views = COALESCE(views, 0) + 1 WHERE id = :id");
        $update->execute(['id' => $property_id]);

        return true;
    }

    // Benzer ilanlar
    public function getSimilarProperties($property_id, $type = null, $location = null, $limit = 6) {
        $limit = max(1, (int) $limit);

        $sql = "SELECT * FROM properties WHERE id != :id AND status = 'approved'";
        $params = ['id' => $property_id];

        if (!empty($type) || !empty($location)) {
            $sql .= " AND (1=0";
            if (!empty($type)) {
                $sql .= " OR type = :type";
                $params['type'] = $type;
            }
            if (!empty($location)) {
                $sql .= " OR location LIKE :location";
                $params['location'] = '%' . $location . '%';
            }
            $sql .= ")";
        }

        $sql .= " ORDER BY created_at DESC LIMIT " . $limit;

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    // Yedek Fonksiyon
    public function getBySlug($slug) {
        return $this->getPropertyBySlug($slug);
    }
}
