<?php

namespace App\Models;

use App\Core\Model;

class Document extends Model
{
    protected $table = 'documents';
    protected $primaryKey = 'id';

    public function getByCategory($categoryId)
    {
        $stmt = $this->db->prepare("SELECT d.*, u.name as uploaded_by_name FROM {$this->table} d LEFT JOIN users u ON d.user_id = u.id WHERE d.category_id = ? ORDER BY d.created_at DESC");
        $stmt->execute([$categoryId]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getPublic()
    {
        $stmt = $this->db->query("SELECT d.*, u.name as uploaded_by_name, c.name as category_name FROM {$this->table} d LEFT JOIN users u ON d.user_id = u.id LEFT JOIN document_categories c ON d.category_id = c.id WHERE d.is_public = 1 ORDER BY d.created_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function incrementDownload($id)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET download_count = download_count + 1 WHERE id = ?");
        $stmt->execute([$id]);
    }
}
