<?php

// includes and security
include_once('../../../../core/includes/master.inc.php');
include_once(DOC_ROOT . '/' . ADMIN_FOLDER_NAME . '/_local_auth.inc.php');

$gRemoveTorrentId = (int) $_REQUEST['gRemoveTorrentId'];

// load plugin details
$pluginDetails  = pluginHelper::pluginSpecificConfiguration('torrentdownload');
$pluginConfig   = $pluginDetails['config'];
$pluginSettings = json_decode($pluginDetails['data']['plugin_settings'], true);
$pluginInstance = pluginHelper::getInstance('torrentdownload');

// prepare result
$result = array();
$result['error'] = false;
$result['msg']   = '';

if (_CONFIG_DEMO_MODE == true)
{
    $result['error'] = true;
    $result['msg']   = adminFunctions::t("no_changes_in_demo_mode");
}
else
{
    // load torrent details
    $torrentData = $db->getRow('SELECT * FROM plugin_torrentdownload_torrent WHERE id='.(int)$gRemoveTorrentId.' LIMIT 1');
    if(!$torrentData)
    {
        $result['error'] = true;
        $result['msg']   = adminFunctions::t("plugin_torrentdownload_could_not_find_torrent", "Could not find torrent.");
    }
    else
    {
        // utorrent library
        require_once('../../uTorrentRemote.class.php');

        // add torrent
        $uTorrentHost = $pluginSettings['utorrent_host'].(strlen($pluginSettings['utorrent_port'])?(':'.$pluginSettings['utorrent_port']):'');
        $uTorrent = new uTorrentRemote($uTorrentHost, $pluginSettings['utorrent_username'], $pluginSettings['utorrent_password']);

        // remove torrent from uTorrent
        $uTorrent->ExecAction('removedata', $torrentData['torrent_hash']);

        // delete local record
        $db->query('DELETE FROM plugin_torrentdownload_torrent_file WHERE torrent_id = :id', array('id' => $torrentData['id']));
        $db->query('DELETE FROM plugin_torrentdownload_torrent WHERE id = :id', array('id' => $torrentData['id']));
        if ($db->affectedRows() == 1)
        {
            $result['error'] = false;
            $result['msg']   = 'Torrent removed.';
        }
        else
        {
            $result['error'] = true;
            $result['msg']   = 'Could not remove torrent, please try again later.';
        }
    }
}

echo json_encode($result);
exit;
