<?php
// app/Models/Property.php

class Property extends Database {

    // Tüm İlanları Getir
    public function getAllProperties() {
        $this->query("SELECT * FROM properties ORDER BY created_at DESC");
        return $this->resultSet();
    }

    // Vitrin (Öne Çıkan) İlanları Getir (Son 6 ilan)
    public function getFeaturedProperties() {
        $this->query("SELECT * FROM properties WHERE status = 'approved' ORDER BY created_at DESC LIMIT 6");
        return $this->resultSet();
    }

    // Tek İlan Detayı Getir (Admin için)
    public function getPropertyById($id) {
        $this->query("SELECT * FROM properties WHERE id = :id");
        $this->bind(':id', $id);
        return $this->single();
    }

    // --- YENİ EKLENENLER (ÖNYÜZ VE ARAMA İÇİN) ---

    // Filtreli İlan Çekme (Kategori, Tip, Fiyat vb.)
    public function getFiltered($filters = []) {
        $sql = "SELECT * FROM properties WHERE 1=1"; 
        $binds = [];

        if (!empty($filters['category'])) {
             $sql .= " AND category = :category";
             $binds[':category'] = $filters['category'];
        }
        if (!empty($filters['type'])) {
             $sql .= " AND type = :type";
             $binds[':type'] = $filters['type'];
        }
        if (!empty($filters['location'])) {
             $sql .= " AND location LIKE :location";
             $binds[':location'] = '%' . $filters['location'] . '%';
        }
        if (!empty($filters['min_price'])) {
             $sql .= " AND price >= :min_price";
             $binds[':min_price'] = $filters['min_price'];
        }
        if (!empty($filters['max_price'])) {
             $sql .= " AND price <= :max_price";
             $binds[':max_price'] = $filters['max_price'];
        }

        $sql .= " ORDER BY created_at DESC";

        $this->query($sql);
        
        // Değişkenleri güvenli şekilde bağla
        foreach($binds as $param => $value) {
            $this->bind($param, $value);
        }

        return $this->resultSet();
    }

    // Slug ile tekil ilan ve danışman bilgilerini getir (Detay Sayfası)
    public function getPropertyBySlug($slug) {
        $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 LIMIT 1";
                
        $this->query($sql);
        $this->bind(':slug', $slug);
        $property = $this->single();

        if ($property) {
            $this->query("SELECT * FROM property_images WHERE property_id = :id ORDER BY is_cover DESC");
            $this->bind(':id', $property->id);
            $property->images = $this->resultSet();
        }

        return $property;
    }

    // --- MEVCUT ADMIN İŞLEMLERİ ---

    public function addProperty($data) {
        $this->query("INSERT INTO properties (user_id, title, slug, description, price, location, features, type, category, status, approved_by, approved_at) VALUES (:user_id, :title, :slug, :description, :price, :location, :features, :type, :category, :status, :approved_by, :approved_at)");

        $this->bind(':user_id', $data['user_id']);
        $this->bind(':title', $data['title']);
        $this->bind(':slug', $data['slug']);
        $this->bind(':description', $data['description']);
        $this->bind(':price', $data['price']);
        $this->bind(':location', $data['location']);
        $this->bind(':features', $data['features']);
        $this->bind(':type', $data['type']);
        $this->bind(':category', $data['category'] ?? null);
        $this->bind(':status', $data['status'] ?? 'pending');
        $this->bind(':approved_by', $data['approved_by'] ?? null);
        $this->bind(':approved_at', $data['approved_at'] ?? null);

        if ($this->execute()) {
            return $this->dbh->lastInsertId();
        }
        return false;
    }

    public function addPropertyImage($property_id, $image_path, $is_cover = 0) {
        $this->query("INSERT INTO property_images (property_id, image_path, is_cover) VALUES (:property_id, :image_path, :is_cover)");
        $this->bind(':property_id', $property_id);
        $this->bind(':image_path', $image_path);
        $this->bind(':is_cover', $is_cover);
        return $this->execute();
    }

    public function updateCoverImage($property_id, $image_path) {
        $this->query("UPDATE properties SET image = :image WHERE id = :id");
        $this->bind(':image', $image_path);
        $this->bind(':id', $property_id);
        $this->execute();
    }

    public function getPropertyImages($id) {
        $this->query("SELECT * FROM property_images WHERE property_id = :id");
        $this->bind(':id', $id);
        return $this->resultSet();
    }

    public function deleteProperty($id) {
        $this->query("DELETE FROM properties WHERE id = :id");
        $this->bind(':id', $id);
        return $this->execute();
    }

    public function updateProperty($data) {
        $this->query("UPDATE properties SET title=:title, slug=:slug, price=:price, type=:type, category=:category, location=:location, description=:description, features=:features WHERE id=:id");
        $this->bind(':id', $data['id']);
        $this->bind(':title', $data['title']);
        $this->bind(':slug', $data['slug']);
        $this->bind(':price', $data['price']);
        $this->bind(':type', $data['type']);
        $this->bind(':category', $data['category'] ?? null);
        $this->bind(':location', $data['location']);
        $this->bind(':description', $data['description']);
        $this->bind(':features', $data['features']);
        return $this->execute();
    }

    public function updateStatus($id, $status, $approved_by = null) {
        $this->query("UPDATE properties SET status = :status, approved_by = :approved_by, approved_at = :approved_at WHERE id = :id");
        $this->bind(':id', $id);
        $this->bind(':status', $status);
        $this->bind(':approved_by', $approved_by);
        $this->bind(':approved_at', ($status === 'approved') ? date('Y-m-d H:i:s') : null);
        return $this->execute();
    }

    public function deleteImageById($image_id) {
        $this->query("DELETE FROM property_images WHERE id = :id");
        $this->bind(':id', $image_id);
        return $this->execute();
    }

    public function getImageById($image_id) {
        $this->query("SELECT * FROM property_images WHERE id = :id");
        $this->bind(':id', $image_id);
        return $this->single();
    }

    public function getPropertiesByUser($user_id) {
        $this->query("SELECT * FROM properties WHERE user_id = :user_id ORDER BY created_at DESC");
        $this->bind(':user_id', $user_id);
        return $this->resultSet();
    }
}