<?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\Response;
use Altum\Traits\Apiable;

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

class ApiStores extends Controller {
    use Apiable;

    public function index() {

        $this->verify_request();

        /* Decide what to continue with */
        switch($_SERVER['REQUEST_METHOD']) {
            case 'GET':

                /* Detect if we only need an object, or the whole list */
                if(isset($this->params[0])) {
                    $this->get();
                } else {
                    $this->get_all();
                }

            break;
        }

        $this->return_404();
    }

    private function get_all() {

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

        /* Prepare the filtering system */
		$filters = (new \Altum\Filters(['is_enabled', 'domain_id'], ['name', 'url'], ['store_id', 'last_datetime', 'datetime', 'pageviews', 'name', 'url', 'orders']));
		$filters->set_default_order_by($this->user->preferences->stores_default_order_by, $this->user->preferences->default_order_type ?? settings()->main->default_order_type);
        $filters->set_default_results_per_page($this->user->preferences->default_results_per_page ?? settings()->main->default_results_per_page);
        $filters->process();

        /* Prepare the paginator */
        $total_rows = database()->query("SELECT COUNT(*) AS `total` FROM `stores` WHERE `user_id` = {$this->user->user_id} {$filters->get_sql_where()}")->fetch_object()->total ?? 0;
        $paginator = (new \Altum\Paginator($total_rows, $filters->get_results_per_page(), $_GET['page'] ?? 1, url('api/stores?' . $filters->get_get() . '&page=%d')));

        /* Get the data */
        $data = [];
        $data_result = database()->query("
            SELECT
                *
            FROM
                `stores`
            WHERE
                `user_id` = {$this->user->user_id}
                {$filters->get_sql_where()}
                {$filters->get_sql_order_by()}
                  
            {$paginator->get_sql_limit()}
        ");
        while($row = $data_result->fetch_object()) {
            $row->full_url = (new \Altum\Models\Store())->get_store_full_url($row, $this->user, $domains);

            /* Prepare the data */
			$row = [
				'store_id' => (int) $row->store_id,
				'domain_id' => (int) $row->domain_id,
				'user_id' => (int) $row->user_id,
				'url' => $row->url,
				'full_url' => $row->full_url,
				'name' => $row->name,
				'description' => $row->description,
				'settings' => json_decode($row->settings ?? ''),
				'details' => json_decode($row->details ?? ''),
				'socials' => json_decode($row->socials ?? ''),
				'currency' => $row->currency,
				'password' => $row->password,
				'image' => $row->image,
				'logo' => $row->logo,
				'favicon' => $row->favicon,
				'opengraph' => $row->opengraph,
				'theme' => $row->theme,
				'timezone' => $row->timezone,
				'custom_css' => $row->custom_css,
				'custom_js' => $row->custom_js,
				'pageviews' => (int) $row->pageviews,
				'orders' => (int) $row->orders,
				'is_se_visible' => (bool) $row->is_se_visible,
				'is_removed_branding' => (bool) $row->is_removed_branding,
				'email_reports_is_enabled' => (bool) $row->email_reports_is_enabled,
				'email_reports_last_datetime' => $row->email_reports_last_datetime,
				'email_orders_is_enabled' => (bool) $row->email_orders_is_enabled,
				'ordering' => json_decode($row->ordering ?? ''),
				'payment_processors' => json_decode($row->payment_processors ?? ''),
				'business' => json_decode($row->business ?? ''),
				'is_enabled' => (bool) $row->is_enabled,
				'datetime' => $row->datetime,
				'last_datetime' => $row->last_datetime
			];

            $data[] = $row;
        }

        /* Prepare the data */
        $meta = [
            'page' => $_GET['page'] ?? 1,
            'total_pages' => $paginator->getNumPages(),
            'results_per_page' => $filters->get_results_per_page(),
            'total_results' => (int) $total_rows,
        ];

        /* Prepare the pagination links */
        $others = ['links' => [
            'first' => $paginator->getPageUrl(1),
            'last' => $paginator->getNumPages() ? $paginator->getPageUrl($paginator->getNumPages()) : null,
            'next' => $paginator->getNextUrl(),
            'prev' => $paginator->getPrevUrl(),
            'self' => $paginator->getPageUrl($_GET['page'] ?? 1)
        ]];

        Response::jsonapi_success($data, $meta, 200, $others);
    }

    private function get() {

        $store_id = isset($this->params[0]) ? (int) $this->params[0] : null;

        /* Try to get details about the resource id */
        $store = db()->where('store_id', $store_id)->where('user_id', $this->user->user_id)->getOne('stores');

        /* We haven't found the resource */
        if(!$store) {
            $this->return_404();
        }

        $store->full_url = (new \Altum\Models\Store())->get_store_full_url($store, $this->user);

        /* Prepare the data */
        $data = [
			'store_id' => (int) $store->store_id,
			'domain_id' => (int) $store->domain_id,
			'user_id' => (int) $store->user_id,
			'url' => $store->url,
			'full_url' => $store->full_url,
			'name' => $store->name,
			'description' => $store->description,
			'settings' => json_decode($store->settings ?? ''),
			'details' => json_decode($store->details ?? ''),
			'socials' => json_decode($store->socials ?? ''),
			'currency' => $store->currency,
			'password' => $store->password,
			'image' => $store->image,
			'logo' => $store->logo,
			'favicon' => $store->favicon,
			'opengraph' => $store->opengraph,
			'theme' => $store->theme,
			'timezone' => $store->timezone,
			'custom_css' => $store->custom_css,
			'custom_js' => $store->custom_js,
			'pageviews' => (int) $store->pageviews,
			'orders' => (int) $store->orders,
			'is_se_visible' => (bool) $store->is_se_visible,
			'is_removed_branding' => (bool) $store->is_removed_branding,
			'email_reports_is_enabled' => (bool) $store->email_reports_is_enabled,
			'email_reports_last_datetime' => $store->email_reports_last_datetime,
			'email_orders_is_enabled' => (bool) $store->email_orders_is_enabled,
			'ordering' => json_decode($store->ordering ?? ''),
			'payment_processors' => json_decode($store->payment_processors ?? ''),
			'business' => json_decode($store->business ?? ''),
			'is_enabled' => (bool) $store->is_enabled,
			'datetime' => $store->datetime,
			'last_datetime' => $store->last_datetime
        ];

        Response::jsonapi_success($data);

    }

}
