<?php

/**
 * Purecharity Plugin
 *
 *
 * @link              http://purecharity.com
 * @since             1.0.0
 * @package           PurecharityPlugin
 *
 * @wordpress-plugin
 * Plugin Name:       Pure Charity
 * Plugin URI:        http://purecharity.com/
 * Description:       Pure Charity Products
 * Version:           3.0.2
 * Author:            Pure Charity
 * Author URI:        http://purecharity.com
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       purecharity-plugin
 * Domain Path:       /languages
 */

namespace PureCharity;

class PcPlugin {

    private $config;

    protected $modules;

    public $moduleConfig;
    public $instance;

    public static $globalModuleResource = 'pcModuleResource';

    function __construct() {

        if (!defined('WPINC')) { die; }

        // Deactivate legacy plugin
        register_activation_hook(__FILE__, [$this, 'coreActivate']);
        
        $version = '3.0.2';

        $this->config = [
            'plugin' => [
                'name' => 'purecharity-plugin',
                'version' => $version,
            ],
            'resourceVersion' => (
                strpos($_SERVER['HTTP_HOST'], '.local') !== false ||
                strpos($_SERVER['HTTP_HOST'], 'loc.') !== false ?
                date('YmdHis') :
                $version
            ),
            'base' => [
                'path' => dirname(__FILE__),
                'url' => plugin_dir_url(__FILE__),
            ],
            'autoload' => [
                'path' => (
                    dirname(__FILE__) .
                    '/modules'
                ),
                'namespace' => 'PureCharity',
                'modules' => [
                    'base' => 'BaseController',
                    'fundraisers' => 'FundraisersController',
                    'sponsorships' => 'SponsorshipsController',
                    'trips' => 'TripsController',
                    // 'giving-circles' => 'GivingCirclesController',
                ],
            ],
            'resources' => [
                'scripts' => plugin_dir_url(__FILE__) .'resources/dist/scripts/',
                'styles' => plugin_dir_url(__FILE__) .'resources/dist/styles/',
                'assets' => [
                    'img' => plugin_dir_url(__FILE__) .'resources/assets/img/',
                ],
            ],
            'templates' => [
                'admin' => dirname(__FILE__) .'/templates/admin/',
                'public' => dirname(__FILE__) .'/templates/public/',
            ],
        ];

        $this->moduleConfig = [
            'resourceVersion' => $this->config['resourceVersion'],
            'base' => $this->config['base'],
            'mainNamespace' => $this->config['autoload']['namespace'],
            'plugin' => $this->config['plugin'],
            'resources' => $this->config['resources'],
            'templates' => $this->config['templates'],
        ];

        $this->modules = [];

        $autoloadState = $this->autoload();

        if (!$autoloadState) {

            $this->dd([
                'Failed Autoloading',
                'Autoload Config:',
                $this->config['autoload'],
            ]);
        }
    }

    public function coreActivate() {

        // The path to the file of the legacy plugin that you want to deactivate
        $legacyPlugin = 'purecharity-wp-base/purecharity-wp-base.php';

        if (is_plugin_active($legacyPlugin)) {
            deactivate_plugins($legacyPlugin);
        }
    }

    private function autoload() {

        if (
            empty($this->config['autoload']['modules']) ||
            !file_exists($this->config['autoload']['path'])
        ) { return false; }

        $modulesDir = scandir($this->config['autoload']['path']);

        if (
            empty($modulesDir) ||
            count($modulesDir) <= 2
        ) { return false; }

        foreach ($this->config['autoload']['modules'] as $namespace => $contoller) {

            if (
                empty($namespace) ||
                empty($contoller)
            ) { continue; }

            $modulePath = (
                $this->config['autoload']['path'] .'/'.
                $namespace .'/'.
                $contoller .'.php'
            );

            if (!file_exists($modulePath)) { continue; } 

            $namespaceUsable = str_replace(
                '-',
                '',
                ucwords($namespace, '-')
            );

            $moduleNamespace = (
                $this->config['autoload']['namespace'] .'\\'.
                $namespaceUsable
            );

            $moduleController = (
                $moduleNamespace .'\\'.
                $contoller
            );

            if (!empty($this->modules[$namespace][$contoller])) { continue; }

            try {
                require_once $modulePath;

                if (empty($this->modules[$namespace])) {
                    $this->modules[$namespace] = [];
                }

                $this->modules[$namespace][$contoller] = new $moduleController($this->moduleConfig);
            } catch (\Error $e) {
                $this->dd($e);
                continue;
            }
        }

        if (
            !empty($this->modules) &&
            count($this->modules) === count($this->config['autoload']['modules'])
        ) {
            return true;
        } else {
            return false;
        }
    }

    public function getModule($module, $controller) {
        $coreInstance = $this->getCoreInstance();

        return (
            !empty($coreInstance->modules[$module]) &&
            !empty($coreInstance->modules[$module][$controller]) ?
            $coreInstance->modules[$module][$controller] :
            null
        );
    }

    public static function dd($data, $shouldDie = true) {
        echo '<pre>';
        var_dump($data);
        echo '</pre>';
        
        if ($shouldDie) {
            die('');
        }
    }

    public static function pluralize($count, $singular, $plural = false) {
        if (!$plural) $plural = $singular . 's';
        return ($count == 1 ? $singular : $plural) ;
    }

    public static function psTruncate($text, $chars = 25) {
        $text = $text." ";
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text = $text."...";
        return $text;
    }

    public function getModuleConfig() {
        return ($this->getCoreInstance())->moduleConfig;
    }

    public function getCoreInstance() {

        if (!empty($this->instance)) {
            return $this->instance;
        } else {
            global $PcPlugin;
            return $PcPlugin;
        }
    }

    public function returnAjaxResponse($success, $data) {
        echo json_encode([
            'success' => $success,
            'data' => $data,
        ]);
        die('');
    }

    public static function handleModuleResource($moduleName, $add = true) {

        if (!isset($GLOBALS[self::$globalModuleResource])) {

            $GLOBALS[self::$globalModuleResource] = [];
        }

        if (
            $add &&
            empty($GLOBALS[self::$globalModuleResource][$moduleName])
        ) {

            $GLOBALS[self::$globalModuleResource][$moduleName] = true;
        } else if (
            !$add &&
            !empty($GLOBALS[self::$globalModuleResource][$moduleName])
        ) {

            unset($GLOBALS[self::$globalModuleResource][$moduleName]);
        }
    }

    public static function moduleResourceExists($moduleName) {

        return (
            !empty($GLOBALS[self::$globalModuleResource]) &&
            !empty($GLOBALS[self::$globalModuleResource][$moduleName])
        );
    }

    public static function truncate($text, $chars)  {
        return self::psTruncate($text, $chars);
    }
}

$PcPlugin = new PcPlugin;

/* ALIAS ps_truncate() */
if(!function_exists('truncate')){
    function truncate($text, $chars = 25) {
        $PcPlugin->psTruncate($text, $chars); 
    }
}