<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Config\Database;
use App\Middleware\AuthMiddleware;
use PDO;

class DeviceController extends Controller {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    public function register() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        
        $this->validate($input, [
            'onesignal_player_id' => 'required',
            'platform' => 'required'
        ]);

        $stmt = $this->db->prepare("INSERT INTO device_players (user_id, onesignal_player_id, platform, created_at) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE onesignal_player_id = VALUES(onesignal_player_id), platform = VALUES(platform)");
        $stmt->execute([$userId, $input['onesignal_player_id'], $input['platform']]);

        $this->json(['success' => true]);
    }

    public function unregister() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        $playerId = isset($input['onesignal_player_id']) ? $input['onesignal_player_id'] : null;

        if ($playerId) {
            $stmt = $this->db->prepare("DELETE FROM device_players WHERE user_id = ? AND onesignal_player_id = ?");
            $stmt->execute([$userId, $playerId]);
        }

        $this->json(['success' => true]);
    }
}
