<?php

namespace Reach\App;

use Reach\App\Interfaces\WordPressHooks;

/**
 * Class PrivacyPolicy
 *
 * @package Reach\App\Fields\Groups
 */
class PrivacyPolicy implements WordPressHooks {

    /**
     * Add class hooks.
     */
    public function addHooks() {
        add_action( 'acf/save_post', [ $this, 'checkForPrivacyPolicyPage' ], 5 );
    }

    /**
     * Check on options save if we have an existing privacy policy page
     *
     * @param $post_id
     *
     * @return bool
     */
    public function checkForPrivacyPolicyPage( $post_id ) {
        // return if not on the options page
        if ( 'options' !== $post_id ) {
            return true;
        }

        // Check for privacy policy page
        $page_args = [
            'post_type'      => 'page',
            'posts_per_page' => 1,
            'no_found_rows'  => true,
            'pagename'       => 'privacy-policy'
        ];

        $privacy_page = new \WP_Query( $page_args );
        // return if we already have a privacy policy page
        if ( ! empty( $privacy_page->posts ) ) {
            return true;
        }

        // Looks like we don't have a privacy policy page, so create one.
        $this->createPrivacyPolicyPage();
    }

    /**
     * Insert a new page for the Privacy Policy
     */
    public function createPrivacyPolicyPage() {
        $content = $this->getPrivacyPolicyContent();

        // Create page object
        $privacy_page = [
            'post_title'   => __( 'Privacy Policy', 'reach' ),
            'post_content' => $content,
            'post_status'  => 'publish',
            'post_type'    => 'page'
        ];

        // Insert the our page
        wp_insert_post( $privacy_page );
    }

    /**
     * Get contents from the privacy policy file and return the string
     *
     * @return string
     */
    public function getPrivacyPolicyContent() {
        $contents = '';
        // check that our xml file exists
        $file = locate_template( 'privacy-policy.xml' );
        if ( ! $file ) {
            return $contents;
        }
        $xml = @simplexml_load_file( $file );

        if ( $xml ) {
            $contents = $xml->asXML();
            $contents = str_replace( [
                '<?xml version="1.0" encoding="UTF-8"?>',
                '<content>',
                '</content>'
            ], '', $contents );
        }

        return $contents;
    }
}