<?php

namespace Dashboard\Controllers\Appearance;

use Dashboard\Core\Controller;

class ThemeFooterController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_THEME');
    }

    public function index()
    {
        return view('appearance.footer.index');
    }

    public function update()
    {
        $_POST = json_decode(file_get_contents('php://input'),true);

        validate([
            "json" => "required"
        ], false);

        if ($_POST["json"] == "" || $_POST["json"] == '{}' || substr($_POST["json"], 0, 1) == '{')
            return false;

        $data = json_decode($_POST["json"], true);
        $idList = array();
        $duplicateIds = array();

        // Find duplicated IDs
        foreach ($data as $item) {
          $id = $item['id'];
          if (in_array($id, $idList)) {
            $duplicateIds[] = $id;
          } else {
            $idList[] = $id;
          }
        }

        // Remove duplicated IDs
        foreach ($duplicateIds as $duplicateId) {
          foreach ($data as $key => $item) {
            if ($item['id'] == $duplicateId) {
              unset($data[$key]);
            }
          }
        }

        $updateSettings = db()->prepare("UPDATE Settings SET value = ? WHERE name = ?");
        $updateSettings->execute(array(json_encode($data), "footer"));
        createLog("THEME_FOOTER_UPDATED");

        response()->json([
            "status" => true,
            "message" => t__('Changes has been saved successfully!')
        ]);
    }
}