<?php
/*
 * Copyright (c) 2026 AltumCode (https://altumcode.com/)
 *
 * This software is licensed exclusively by AltumCode and is sold only via https://altumcode.com/.
 * Unauthorized distribution, modification, or use of this software without a valid license is not permitted and may be subject to applicable legal actions.
 *
 * 🌍 View all other existing AltumCode projects via https://altumcode.com/
 * 📧 Get in touch for support or general queries via https://altumcode.com/contact
 * 📤 Download the latest version via https://altumcode.com/downloads
 *
 * 🐦 X/Twitter: https://x.com/AltumCode
 * 📘 Facebook: https://facebook.com/altumcode
 * 📸 Instagram: https://instagram.com/altumcode
 */

namespace Altum\Controllers;

use Altum\Alerts;

defined('ALTUMCODE') || die();

class ItemExtra extends Controller {

    public function index() {

        die();

    }

    public function delete() {

        \Altum\Authentication::guard();

        /* Team checks */
        if(\Altum\Teams::is_delegated() && !\Altum\Teams::has_access('delete.items')) {
            Alerts::add_error(l('global.info_message.team_no_access'));
            redirect('dashboard');
        }

        if (empty($_POST)) {
            throw_404();
        }

        $item_extra_id = (int) $_POST['item_extra_id'];

        //ALTUMCODE:DEMO if(DEMO) if($this->user->user_id == 1) Alerts::add_error('Please create an account on the demo to test out this function.');

        if(!\Altum\Csrf::check()) {
            Alerts::add_error(l('global.error_message.invalid_csrf_token'));
        }

        /* Make sure the store id is created by the logged in user */
        if(!$item_extra = db()->where('user_id', $this->user->user_id)->where('item_extra_id', $item_extra_id)->getOne('items_extras', ['store_id', 'menu_id', 'category_id', 'item_id', 'item_extra_id', 'name'])) {
            throw_404();
        }

        if(!Alerts::has_field_errors() && !Alerts::has_errors()) {

            /* Delete the menu */
            db()->where('item_extra_id', $item_extra->item_extra_id)->delete('items_extras');

            /* Clear the cache */
            cache()->deleteItemsByTag('store_id=' . $item_extra->store_id);

            /* Set a nice success message */
            Alerts::add_success(sprintf(l('global.success_message.delete1'), '<strong>' . $item_extra->name . '</strong>'));

            redirect('item/' . $item_extra->item_id);

        }

        redirect('item/' . $item_extra->item_id);
    }
}
