<?php

App::uses('AppController', 'Controller');

/**
 * Planos Controller
 *
 * @property Plano $Plano
 * @property PaginatorComponent $Paginator
 * @property SessionComponent $Session
 */
class SitemapController extends AppController
{

    /**
     * Components
     *
     * @var array
     */
    public $components = array(
        'RequestHandler'
    );

    /**
     * beforeFilter
     *
     * @return void
     */
    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow(
            'index',
            'robots'
        );
    }

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {
        $this->viewClass = 'Xml';

        $this->loadModel('Music');
        $this->Music->recursive = 0;

        $condition = array(
            'fields' => array(
                'Music.slug',
                'Music.name',
                'Music.created',
            ),
            'conditions' => array(
                'Music.in_trash' => false,
            ),
            'order' => 'Music.created DESC'
        );

        $musics = $this->Music->find("all", $condition);
        $xml = array(
            'urlset' => array(
                'xmlns:' => 'https://www.sitemaps.org/schemas/sitemap/0.9',
                'url' => array()
            )
        );

        $urls = array();
        foreach ($musics as $ms) {
            $datetime = new DateTime($ms['Music']['created']);
            array_push($urls, array(
                'loc' => sprintf('%s/music/%s', Configure::read('Service.akismet_url'), $ms['Music']['slug']),
                'lastmod' => $datetime->format('Y-m-d')
            ));
        }
        $xml['urlset']['url'] = $urls;

        $this->set(compact('xml'));
        $this->set('_serialize', 'xml');
    }

    /**
     * index method
     *
     * @return void
     */
    public function robots()
    {
        $this->RequestHandler->respondAs('text');
        $this->viewPath .= '/text';
        $this->layout = 'ajax';
    }
}

