<?php

namespace App\Services;

require_once __DIR__ . '/../../db/config.php';

class ApkService {
    protected $db;

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

    public function getLatest($limit = 10) {
        $stmt = $this->db->prepare("SELECT * FROM apks WHERE status = 'published' ORDER BY display_order ASC, created_at DESC LIMIT :limit");
        $stmt->bindValue(':limit', (int)$limit, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function getBySlug($slug) {
        $stmt = $this->db->prepare("SELECT * FROM apks WHERE slug = :slug AND status = 'published' LIMIT 1");
        $stmt->execute(['slug' => $slug]);
        return $stmt->fetch();
    }

    public function getAllApks($category_slug = null, $search = null) {
        $query = "SELECT a.* FROM apks a";
        $params = [];
        $where = [];

        if ($category_slug) {
            $query .= " JOIN categories c ON a.category_id = c.id";
            $where[] = "c.slug = :category_slug";
            $params['category_slug'] = $category_slug;
        }

        if ($search) {
            $where[] = "a.title LIKE :search";
            $params['search'] = "%$search%";
        }

        if (!empty($where)) {
            $query .= " WHERE " . implode(" AND ", $where);
        }

        $query .= " ORDER BY a.display_order ASC, a.created_at DESC";

        $stmt = $this->db->prepare($query);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    public function getApkById($id) {
        $stmt = $this->db->prepare("SELECT * FROM apks WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public function incrementDownload($apkId) {
        $stmt = $this->db->prepare("UPDATE apks SET total_downloads = total_downloads + 1 WHERE id = :id");
        $stmt->execute(['id' => $apkId]);

        $stmt = $this->db->prepare("INSERT INTO downloads (apk_id, ip_address) VALUES (:apk_id, :ip)");
        $stmt->execute([
            'apk_id' => $apkId,
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'
        ]);
    }
}