<?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 StoreCreate extends Controller {

    public function index() {

        \Altum\Authentication::guard();

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

        /* Check for the plan limit */
        $total_rows = database()->query("SELECT COUNT(*) AS `total` FROM `stores` WHERE `user_id` = {$this->user->user_id}")->fetch_object()->total ?? 0;

        if($this->user->plan_settings->stores_limit != -1 && $total_rows >= $this->user->plan_settings->stores_limit) {
            Alerts::add_error(l('global.info_message.plan_feature_limit') . (settings()->payment->is_enabled ? ' <a href="' . url('plan') . '" class="font-weight-bold text-reset">' . l('global.info_message.plan_upgrade') . '.</a>' : null));
            redirect('dashboard');
        }

        /* Get available custom domains */
        $domains = (new \Altum\Models\Domain())->get_available_domains_by_user($this->user);

        if(!empty($_POST)) {
            $_POST['url'] = !empty($_POST['url']) && $this->user->plan_settings->custom_url_is_enabled ? get_slug(query_clean($_POST['url'])) : false;
            $_POST['name'] = trim(query_clean($_POST['name']));
            $_POST['description'] = trim(query_clean($_POST['description']));
            $_POST['address'] = trim(query_clean($_POST['address']));
            $_POST['currency'] = trim(query_clean($_POST['currency']));
            $_POST['timezone'] = in_array($_POST['timezone'], \DateTimeZone::listIdentifiers()) ? query_clean($_POST['timezone']) : settings()->main->default_timezone;

            $_POST['domain_id'] = isset($_POST['domain_id']) && isset($domains[$_POST['domain_id']]) ? (!empty($_POST['domain_id']) ? (int) $_POST['domain_id'] : null) : null;
            $_POST['is_main_store'] = isset($_POST['is_main_store']) && isset($domains[$_POST['domain_id']]) && $domains[$_POST['domain_id']]->type == 0;

            //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.');

            /* Check for any errors */
            if(!\Altum\Csrf::check()) {
                Alerts::add_error(l('global.error_message.invalid_csrf_token'));
            }

            /* Check for duplicate url if needed */
            if($_POST['url']) {

                if(array_key_exists($_POST['url'], \Altum\Router::$routes['']) || in_array($_POST['url'], \Altum\Language::$active_languages) || file_exists(ROOT_PATH . $_POST['url'])) {
                    Alerts::add_field_error('url', l('store.error_message.blacklisted_url'));
                }

                $domain_id_where = $_POST['domain_id'] ? "AND `domain_id` = {$_POST['domain_id']}" : "AND `domain_id` IS NULL";
                $is_existing_store = database()->query("SELECT `store_id` FROM `stores` WHERE `url` = '{$_POST['url']}' {$domain_id_where}")->num_rows;

                if($is_existing_store) {
                    Alerts::add_error(l('store.error_message.url_exists'));
                }

                if(!$_POST['is_main_store']) {
                    /* Make sure the custom url meets the requirements */
                    if(mb_strlen($_POST['url']) < ($this->user->plan_settings->url_minimum_characters ?? 1)) {
                        Alerts::add_error(sprintf(l('store.error_message.url_minimum_characters'), ($this->user->plan_settings->url_minimum_characters ?? 1)));
                    }

                    if(mb_strlen($_POST['url']) > ($this->user->plan_settings->url_maximum_characters ?? 64)) {
                        Alerts::add_error(sprintf(l('store.error_message.url_maximum_characters'), ($this->user->plan_settings->url_maximum_characters ?? 64)));
                    }
                }
            }

            if(!Alerts::has_field_errors() && !Alerts::has_errors()) {
                $details = json_encode([
                    'address' => $_POST['address'],
                    'phone' => '',
                    'website' => '',
                    'email' => '',
                    'hours' => [
                        '1' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '2' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '3' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '4' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '5' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '6' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ],
                        '7' => [
                            'is_enabled' => 1,
                            'hours' => '',
                        ]
                    ]
                ]);
                $settings = json_encode([
                    'title' => null,
                    'meta_description' => null,
                    'meta_keywords' => null,
                    'font_family' => 'default',
                    'font_size' => 16,
                    'display_share_buttons' => true,
                    'auto_refresh' => 15,

                    'pwa_file_name' => null,
                    'pwa_is_enabled' => false,
                    'pwa_icon' => null,
                    'pwa_display_install_bar' => null,
                    'pwa_display_install_bar_delay' => 3,
                    'pwa_theme_color' => null,
                ]);

                $ordering = json_encode([
                    'on_premise_is_enabled' => true,
                    'delivery_is_enabled' => true,
                    'takeaway_is_enabled' => true,
                    'on_premise_minimum_value' => 1,
                    'delivery_minimum_value' => 1,
                    'delivery_cost' => 0,
                    'delivery_free_minimum_value' => 0,
                    'takeaway_minimum_value' => 1,
                ]);

                $payment_processors = json_encode([
                    'paypal_is_enabled' => null,
                    'paypal_mode' => null,
                    'paypal_client_id' => null,
                    'paypal_secret' => null,

                    'stripe_is_enabled' => null,
                    'stripe_publishable_key' => null,
                    'stripe_secret_key' => null,
                    'stripe_webhook_secret' => null,

                    'mollie_is_enabled' => null,
                    'mollie_api_key' => null,

                    'offline_payment_is_enabled' => null,
                ]);

                $business = json_encode([
                    'invoice_is_enabled' => null,
                    'invoice_nr_prefix' => null,
                    'name' => null,
                    'address' => null,
                    'city' => null,
                    'county' => null,
                    'zip' => null,
                    'country' => null,
                    'email' => null,
                    'phone' => null,
                    'tax_type' => null,
                    'tax_id' => null,
                    'custom_key_one' => null,
                    'custom_value_one' => null,
                    'custom_key_two' => null,
                    'custom_value_two' => null,
                ]);

                $theme = 'new-york';

                if(!$_POST['url']) {
                    $is_existing_store = true;

                    /* Generate random url if not specified */
                    while($is_existing_store) {
                        $_POST['url'] = mb_strtolower(string_generate(settings()->stores->random_url_length ?? 7));

                        $domain_id_where = $_POST['domain_id'] ? "AND `domain_id` = {$_POST['domain_id']}" : "AND `domain_id` IS NULL";
                        $is_existing_store = database()->query("SELECT `store_id` FROM `stores` WHERE `url` = '{$_POST['url']}' {$domain_id_where}")->num_rows;
                    }

                }

                /* Socials */
                $socials = [];

                foreach(require APP_PATH . 'includes/s/socials.php' as $key => $value) {
                    $socials[$key] = null;
                }

                $socials = json_encode($socials);

                /* Database query */
                $store_id = db()->insert('stores', [
                    'user_id' => $this->user->user_id,
                    'domain_id' => $_POST['domain_id'],
                    'url' => $_POST['url'],
                    'name' => $_POST['name'],
                    'description' => $_POST['description'],
                    'settings' => $settings,
                    'details' => $details,
                    'ordering' => $ordering,
                    'payment_processors' => $payment_processors,
                    'business' => $business,
                    'socials' => $socials,
                    'currency' => $_POST['currency'],
                    'theme' => $theme,
                    'timezone' => $_POST['timezone'],
                    'email_reports_last_datetime' => get_date(),
                    'datetime' => get_date(),
                ]);



                /* Update custom domain if needed */
                if($_POST['is_main_store']) {
                    db()->where('domain_id', $_POST['domain_id'])->update('domains', [
                        'store_id' => $store_id,
                        'last_datetime' => get_date(),
                    ]);

                    /* Clear the cache */
                    cache()->deleteItems([
                        'domains?user_id=' . $this->user->user_id,
                        'domain?domain_id=' . $_POST['domain_id'],
                        'domain?host=' . md5($domains[$_POST['domain_id']]->host ?? ''),
                    ]);
                    cache()->deleteItemsByTag('domains?user_id=' . $this->user->user_id);
                }

                /* Clear the cache */
                cache()->deleteItem('stores_total?user_id=' . $this->user->user_id);

                /* Set a nice success message */
                Alerts::add_success(sprintf(l('global.success_message.create1'), '<strong>' . $_POST['name'] . '</strong>'));

                redirect('store/' . $store_id);
            }

        }

        /* Set default values */
        $values = [
            'url' => $_POST['url'] ?? '',
            'name' => $_POST['name'] ?? '',
            'description' => $_POST['description'] ?? '',
            'address' => $_POST['address'] ?? '',
            'currency' => $_POST['currency'] ?? '',
            'timezone' => $_POST['timezone'] ?? '',
            'domain_id' => $_POST['domain_id'] ?? '',
            'is_main_store' => $_POST['is_main_store'] ?? '',
        ];

        /* Prepare the view */
        $data = [
            'domains' => $domains,
            'values' => $values
        ];

        $view = new \Altum\View('store-create/index', (array) $this);

        $this->add_view_content('content', $view->run($data));

    }

}
