<?php
class Product
{
    private $conn;

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

    // دریافت همه محصولات
    public function getAll($sortByTime = "DESC", $sortByLike = "DESC")
    {
        // مرتب‌سازی پویا
        $orderBy = [];
        $orderBy[] = "p.likes_count " . ($sortByLike == "ASC" ? "ASC" : "DESC");
        $orderBy[] = "p.created_at " . ($sortByTime == "ASC" ? "ASC" : "DESC");

        // ثبت لاگ
        $logQuery = $this->conn->prepare("INSERT INTO logs (action) VALUES (:action)");
        $logQuery->execute([':action' => 'Sort: ' . implode(", ", $orderBy)]);

        // کوئری اصلی — join با جدول ratings برای محاسبه میانگین
        $query = "
        SELECT 
            p.*, 
            ROUND(AVG(r.rating), 2) AS average_rating,
            COUNT(r.id) AS total_ratings
        FROM products p
        LEFT JOIN product_ratings r ON p.id = r.product_id
        GROUP BY p.id
        ORDER BY " . implode(", ", $orderBy);

        $stmt = $this->conn->query($query);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }



    // دریافت یک محصول با id
    public function get($id)
    {
        $stmt = $this->conn->prepare("SELECT * FROM products WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    public function getDealOfTheDay()
    {
        $stmt = $this->conn->prepare("
    SELECT * 
    FROM products 
    WHERE deal_of_the_day = 1 
    ORDER BY created_at ASC 
    LIMIT 1
");

        $stmt->execute();
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        return $product;
    }
    public function getDiscount()
    {
        $stmt = $this->conn->prepare("
    SELECT * 
    FROM products 
    WHERE discount > 0 
    ORDER BY created_at ASC 
");

        $stmt->execute();
        $product = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $product;
    }

    // ایجاد محصول
    public function create($data)
    {
        $stmt = $this->conn->prepare("INSERT INTO products 
            (name, description, price, discount, category_id, image_path, stock, material, dimensions, weight) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['name'],
            $data['description'],
            $data['price'],
            $data['discount'] ?? 0,
            $data['category_id'] ?? null,
            $data['image_path'] ?? null,
            $data['stock'] ?? 0,
            $data['material'] ?? null,
            $data['dimensions'] ?? null,
            $data['weight'] ?? null
        ]);
        return $this->conn->lastInsertId();
    }

    // بروزرسانی محصول
    public function update($id, $data)
    {
        $stmt = $this->conn->prepare("UPDATE products SET 
            name=?, description=?, price=?, discount=?, category_id=?, image_path=?, stock=?, material=?, dimensions=?, weight=? 
            WHERE id=?");
        return $stmt->execute([
            $data['name'],
            $data['description'],
            $data['price'],
            $data['discount'] ?? 0,
            $data['category_id'] ?? null,
            $data['image_path'] ?? null,
            $data['stock'] ?? 0,
            $data['material'] ?? null,
            $data['dimensions'] ?? null,
            $data['weight'] ?? null,
            $id
        ]);
    }

    // حذف محصول
    public function delete($id)
    {
        $stmt = $this->conn->prepare("DELETE FROM products WHERE id=?");
        return $stmt->execute([$id]);
    }
    public function uploadAlbums($id, $files)
    {
        $uploadDir = __DIR__ . '/../../../uploads/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $stmt = $this->conn->prepare("SELECT albums FROM products WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $albums = [];
        if (!empty($row['albums'])) {
            $decoded = json_decode($row['albums'], true);
            if (is_array($decoded))
                $albums = $decoded;
        }

        $newFiles = [];
        foreach ($files['tmp_name'] as $key => $tmpName) {
            if (!empty($tmpName) && is_uploaded_file($tmpName)) {
                $name = time() . '_' . uniqid() . '_' . basename($files['name'][$key]);
                $targetPath = $uploadDir . $name;
                if (move_uploaded_file($tmpName, $targetPath)) {
                    $newFiles[] = $name;
                }
            }
        }

        $albums = array_merge($albums, $newFiles);
        $albumsJson = json_encode($albums, JSON_UNESCAPED_UNICODE);

        $update = $this->conn->prepare("UPDATE products SET albums = ? WHERE id = ?");
        $update->execute([$albumsJson, $id]);

        return $albums;
    }
}