<?php
/**
 * Review Model
 */

class Review {
    private $pdo;

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

    /**
     * Create review
     */
    public function create($data) {
        $stmt = $this->pdo->prepare("
            INSERT INTO reviews (reviewer_name, reviewer_email, rating, review_text, image_path, is_featured)
            VALUES (:reviewer_name, :reviewer_email, :rating, :review_text, :image_path, :is_featured)
        ");

        return $stmt->execute([
            ':reviewer_name' => $data['reviewer_name'] ?? '',
            ':reviewer_email' => $data['reviewer_email'] ?? '',
            ':rating' => $data['rating'] ?? 5,
            ':review_text' => $data['review_text'] ?? '',
            ':image_path' => $data['image_path'] ?? null,
            ':is_featured' => $data['is_featured'] ?? false
        ]);
    }

    /**
     * Get all reviews
     */
    public function getAll($limit = 50, $offset = 0) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM reviews 
            ORDER BY created_at DESC 
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    /**
     * Get featured reviews
     */
    public function getFeatured($limit = 6) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM reviews 
            WHERE is_featured = TRUE 
            ORDER BY created_at DESC 
            LIMIT :limit
        ");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    /**
     * Get review by ID
     */
    public function getById($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM reviews WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->fetch();
    }

    /**
     * Update review
     */
    public function update($id, $data) {
        $fields = [];
        $params = [':id' => $id];

        foreach ($data as $key => $value) {
            $fields[] = "$key = :$key";
            $params[":$key"] = $value;
        }

        $sql = "UPDATE reviews SET " . implode(', ', $fields) . " WHERE id = :id";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($params);
    }

    /**
     * Delete review
     */
    public function delete($id) {
        $stmt = $this->pdo->prepare("DELETE FROM reviews WHERE id = :id");
        return $stmt->execute([':id' => $id]);
    }

    /**
     * Get count
     */
    public function getCount() {
        $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM reviews");
        $result = $stmt->fetch();
        return $result['count'];
    }
}
