<?php

namespace DJMixHosting;

class Playcount
{

    private $db;
    private $mix_id;

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

    public function getPlaycount()
    {
        $sql = "SELECT value FROM mix_meta WHERE mix_id = ? AND attribute = 'playcount'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->mix_id]);
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        return $row['value'];
    }

    public function updatePlaycount(): void
    {
        if ($this->checkForPlaycount()) {
            $this->incrementPlaycount();
        } else {
            $this->addPlaycount();
        }
    }

    private function checkForPlaycount()
    {
        $sql = "SELECT meta_id FROM mix_meta WHERE mix_id = ? AND attribute = 'playcount'";
        $stmt = $this->db->prepare($sql);
        $stmt->bind_param('i', $this->mix_id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    private function incrementPlaycount()
    {
        $sql = "UPDATE mix_meta SET value = value + 1 WHERE mix_id = ? AND attribute = 'playcount'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->mix_id]);
    }

    public function addPlaycount()
    {
        $sql = "INSERT INTO mix_meta (mix_id, attribute, value) VALUES (?, 'playcount', 1)";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->mix_id]);
    }


}