<?php declare(strict_types=1);

/**
 * Add/Edit/Delete Feed Page
 *
 * Allows users to add, edit, and delete feeds
 */

use BitBadger\Documents\DocumentException;
use BitBadger\Documents\Field;
use BitBadger\Documents\SQLite\Configuration;
use BitBadger\Documents\SQLite\Delete;
use FeedReaderCentral\Feed;
use FeedReaderCentral\Security;
use FeedReaderCentral\Table;

include '../../start.php';

Security::verifyUser();

$feedId = $_GET['id'] ?? '';

if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
    try {
        if (!($feed = Feed::retrieveById($feedId))) not_found();
        Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]);
        Delete::byId(Table::FEED, $feed->id);
        add_info('Feed &ldquo;' . htmlentities($feed->title) . '&rdquo; deleted successfully');
        frc_redirect('/feeds');
    } catch (DocumentException $ex) {
        add_error("$ex");
    }
}

$db = Configuration::dbConn();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $isNew = $_POST['id'] == 'new';
        if ($isNew) {
            $result = Feed::add($_POST['url'], $db);
        } else {
            $toEdit = Feed::retrieveById($_POST['id']);
            $result = $toEdit
                ? Feed::update($toEdit, $_POST['url'], $db)
                : ['error' => "Feed {$_POST['id']} not found"];
        }
        if (key_exists('ok', $result)) {
            add_info('Feed saved successfully');
            $db->close();
            frc_redirect('/feeds');
        }
        add_error($result['error']);
        $feedId = 'error';
    } catch (DocumentException $ex) {
        add_error("$ex");
    }
}

if ($feedId == 'new') {
    $title    = 'Add RSS Feed';
    $feed     = new Feed();
    $feed->id = $_GET['id'];
} else {
    $title = 'Edit RSS Feed';
    if ($feedId == 'error') {
        $feed      = new Feed();
        $feed->id  = $_POST['id'] ?? '';
        $feed->url = $_POST['url'] ?? '';
    } elseif (!($feed = Feed::retrieveById((int)$feedId))) not_found();
}

page_head($title); ?>
<h1><?=$title?></h1>
<article>
    <form method=POST action=/feed/ hx-post=/feed/>
        <input type=hidden name=id value=<?=$feed->id?>>
        <label>
            Feed URL
            <input type=url name=url required autofocus value="<?=$feed->url?>">
        </label>
        <span class=break></span>
        <button type=submit>Save</button>
    </form>
</article><?php
page_foot();
$db->close();