<?php namespace App\Controllers;

use App\Models\WebStoryModel;

class WebStoryController extends BaseController
{
    protected $storyModel;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->storyModel = new WebStoryModel();
    }

    /**
     * Public Web Stories Listing Page
     */
    public function index()
    {
        $data = [
            'pageType'    => 'web_stories',
            'title'       => trans("web_stories") ?? 'Web Stories',
            'description' => $this->settings->site_description,
            'keywords'    => $this->settings->keywords,
            'activeLang'  => $this->activeLang,
            'userSession' => getUserSession(),
            'stories'     => $this->storyModel->where('lang_id', $this->activeLang->id)
                                              ->where('status', 1)
                                              ->where('visibility', 1)
                                              ->orderBy('created_at', 'DESC')
                                              ->paginate($this->postsPerPage ?? 12),
            'pager'       => $this->storyModel->pager
        ];

        
        return loadView('web_story/stories', $data);
    }

    /**
     * Frontend View for Single Story (AMP)
     */
    public function viewStory($slug)
    {
        $slug = cleanSlug($slug);
        
        $story = $this->storyModel->getActiveStoryBySlug($slug, $this->activeLang->id);

        if (empty($story)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $this->storyModel->incrementPageviews($story->id);

        $data = [
            'story'              => $story,
            'activeLang'         => $this->activeLang,
            'settings'           => $this->settings,
            'generalSettings'    => $this->generalSettings ?? null,
            'recommendedStories' => $this->storyModel->getRecommendedStories($this->activeLang->id, $story->id, 4)
        ];

        return loadView('web_story/view', $data);
    }

    // ==========================================
    // SITEMAP GENERATOR (BULLETPROOF METHOD)
    // ==========================================
    public function sitemap()
    {
        $stories = $this->storyModel->getSitemapStories();

        if (ob_get_level()) { ob_end_clean(); }
        header("Content-Type: text/xml; charset=utf-8");

        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "\n";

        if (!empty($stories)) {
            foreach ($stories as $story) {
                $xml .= '    <url>' . "\n";
                $xml .= '        <loc>' . base_url('web-stories/' . $story->slug) . '</loc>' . "\n";
                $xml .= '        <lastmod>' . date('Y-m-d\TH:i:sP', strtotime($story->updated_at ?? $story->created_at)) . '</lastmod>' . "\n";
                $xml .= '        <priority>0.9</priority>' . "\n";
                $xml .= '    </url>' . "\n";
            }
        }
        
        $xml .= '</urlset>';
        echo $xml;
        exit;
    }

    // ==========================================
    // RSS GENERATOR (BULLETPROOF METHOD)
    // ==========================================
    public function rss()
    {
        $stories = $this->storyModel->getRssStories($this->activeLang->id, 50);
        $feedName = xmlEscape($this->settings->site_title . ' - Web Stories');
        $feedUrl = langBaseUrl('rss/web-stories');
        $pageDescription = xmlEscape($this->settings->site_description);
        $pageLanguage = $this->activeLang->short_form;

        if (ob_get_level()) { ob_end_clean(); }
        header("Content-Type: application/rss+xml; charset=utf-8");

        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n";
        $xml .= '    <channel>' . "\n";
        $xml .= '        <title>' . $feedName . '</title>' . "\n";
        $xml .= '        <link>' . $feedUrl . '</link>' . "\n";
        $xml .= '        <description>' . $pageDescription . '</description>' . "\n";
        $xml .= '        <language>' . $pageLanguage . '</language>' . "\n";
        $xml .= '        <atom:link href="' . $feedUrl . '" rel="self" type="application/rss+xml"/>' . "\n";

        if (!empty($stories)) {
            foreach ($stories as $story) {
                $xml .= '        <item>' . "\n";
                $xml .= '            <title>' . xmlEscape($story->title) . '</title>' . "\n";
                $xml .= '            <link>' . base_url('web-stories/' . $story->slug) . '</link>' . "\n";
                $xml .= '            <guid isPermaLink="true">' . base_url('web-stories/' . $story->slug) . '</guid>' . "\n";
                $xml .= '            <description><![CDATA[' . cleanXmlData($story->summary) . ']]></description>' . "\n";

                if (!empty($story->cover_image)) {
                    $imageUrl = strpos($story->cover_image, 'http') === 0 ? $story->cover_image : base_url($story->cover_image);
                    $xml .= '            <enclosure url="' . $imageUrl . '" length="0" type="image/jpeg"/>' . "\n";
                }

                $xml .= '            <pubDate>' . date('r', strtotime($story->created_at)) . '</pubDate>' . "\n";
                $xml .= '        </item>' . "\n";
            }
        }

        $xml .= '    </channel>' . "\n";
        $xml .= '</rss>';
        echo $xml;
        exit;
    }
}