<?php
/**
* 2023 Anvanto
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
*
*  @author    Anvanto <anvantoco@gmail.com>
*  @copyright 2023 Anvanto
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*/

class anHomecatFiles
{
    public function __construct()
    {
        $this->themeDir = Context::getContext()->shop->theme->getDirectory();
        $this->themeName = Context::getContext()->shop->theme->getName();
        
        $this->moduleDir = _PS_MODULE_DIR_ . 'an_homecategories/';

        $this->contentDir = $this->themeDir.'assets/antheme/an_homecategories/';
        $this->contentImgDir = $this->themeDir.'assets/antheme/an_homecategories/img/';
        $this->imgDir = __PS_BASE_URI__.'img/an_homecategories/';
        $this->jsonContentFile = $this->themeDir.'assets/antheme/an_homecategories/homecategories.json';
        $this->jsonSettingsFile = $this->themeDir.'assets/antheme/an_homecategories/settings.json';
    
        $this->jsonContentFileOld = _PS_MODULE_DIR_ . 'an_homecategories/homecategories.json';
        $this->jsonSettingsFileOld = _PS_MODULE_DIR_ . 'an_homecategories/settings.json';
    }



    



    public function getContentFilePath()
    { 
        return $this->getContentDir() . 'homecategories.json';
    }

    public function getSettingsFilePath()
    { 
        return $this->getContentDir() . 'settings.json';
    }

    public function getContentDir()
    { 
        $this->createFolders();

        if (Tools::file_exists_no_cache($this->contentDir)){
            return $this->contentDir;
        }

        return $this->moduleDir;
    }

    public function getContentFile()
    { 
        if (Tools::file_exists_no_cache($this->jsonContentFile)){
            return Tools::file_get_contents($this->jsonContentFile);
        } else if (Tools::file_exists_no_cache($this->jsonContentFileOld)){
            return Tools::file_get_contents($this->jsonContentFileOld);
        }
        return '';
    }

    public function getSettingsFile()
    { 
        if (Tools::file_exists_no_cache($this->jsonSettingsFile)){
            return Tools::file_get_contents($this->jsonSettingsFile);
        } else if (Tools::file_exists_no_cache($this->jsonSettingsFileOld)){
            return Tools::file_get_contents($this->jsonSettingsFileOld);
        }
        return '';
    }

    public function createFolders()
    {
        $this->checkCreateFolder($this->contentDir);
        $this->checkCreateFolder($this->contentImgDir);
    }    

    public function checkCreateFolder($path)
    {
        if (!Tools::file_exists_no_cache($path)){
            mkdir($path, 0777, true);
            Tools::copy($this->moduleDir . 'index.php', $path . 'index.php');
        }
    }   

}