<?php

namespace Filanco\Cms\Models;

use Filanco\Cms\Models\Page;
use Filanco\Cms\Models\Post;
use Filanco\Cms\Models\Category;
use Symfony\Component\HttpFoundation\Request;


class Sitemap
{

    protected $fileMap = null;
    protected $host = null;
    protected $map = null;
    public $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
             <urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    public $footer = "</urlset>";


    public function __construct($fileMap = null)
    {

        if (isset($fileMap)) {
            $this->fileMap = $fileMap;
        } else {
            $this->fileMap = public_path('sitemap.xml');
        }

        $this->host = $_SERVER['HTTP_HOST'];


    }

    /** Получение даты создание файла
     * @return false|string
     */
    public function getFileCreate()
    {
        if (\file_exists($this->fileMap)) {
            return date("d.n.Y H:i:s.", filectime($this->fileMap));
        } else {
            return 'Карта не найдена';
        }
    }


    /**Генерация страниц
     * @return null
     */
    private function getAllPages()
    {
        $pages = Page::where('status', '=', 'ACTIVE')->get()->toArray();
        foreach ($pages as $page) {
            $this->map .= $this->link($page['slug']);
        }
        return $this->map;
    }

    /**Генерация постов
     * @return null
     */
    private function getAllPosts()
    {
        // $posts = Post::where('status', '=', 'PUBLISHED')->join('category', 'catehory.id', '=', 'orders.user_id')->get()->toArray();

        $posts = Post::where('status', '=', 'PUBLISHED')->with('category')->get()->toArray();

        foreach ($posts as $post) {
            $this->map .= $this->link( $post['category']['slug'] . "/" . $post['slug']);
        }

        return $this->map;

    }


    /**Создаем ссылку
     * @param $url
     * @param float $priority
     * @return string
     */
    private function link($url, $priority = 0.5)
    {
        return "<url>
                <loc>" . (new Request())->getScheme() . "://" . $this->host . "/" . $url . "</loc>
                <changefreq>weekly</changefreq>
                <priority>" . $priority . "</priority>
                </url>";
    }


    public function create()
    {

        try {
            $this->map = $this->header;
            $this->getAllPages();
            $this->getAllPosts();
            $this->map .= $this->footer;
            file_put_contents($this->fileMap, $this->map, LOCK_EX);

            return true;

        } catch (Exception $e) {
            return $e;
        }


    }


}
