<?php
    /*
            *****************************************************************************
            * MEGA Digital Space - by MEGA Digital Studio                               *
            * ------------------------------------------------------------------------- *
            * CMS Website:  https://megadigital.space                                   *
            * License:  https://megadigital.space/license                               *
            * Owner:  Giorgi Basharuli                                                  *
            * Contact:  online@megadigital.studio                                       *
            * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
            * Website:  https://megadigital.studio                                      *
            * ------------------------------------------------------------------------- *
            * Description: This file is a part of the MEGA Digital Space CMS system.    *
            * Unauthorized distribution, modification, or commercial use is strictly -  *
            * prohibited without prior written permission.                              *
            * ------------------------------------------------------------------------- *
            * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
            * All rights reserved.                                                      *
            *****************************************************************************
        */

    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json");

    global $db_connect;

    $input = json_decode(file_get_contents('php://input'), true);

    $code        = $input['code'] ?? null;
    $storeRegion = $input['store_region'] ?? null;
    $apiKey      = $input['api_key'] ?? null;
    $orderAmount = isset($input['order_amount']) ? (float)$input['order_amount'] : null;

    if ($apiKey !== 'SECRET_API_KEY_FOR_SHOP') {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'unauthorized']);
        exit;
    }

    if (!$code) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'missing_code']);
        exit;
    }

    $token = $db_connect->get('qr_tokens', '*', [
        'code' => $code
    ]);

    if (!$token) {
        echo json_encode(['success' => false, 'error' => 'invalid_code']);
        exit;
    }

    if (!empty($token['expires_at']) && strtotime($token['expires_at']) < time()) {
        echo json_encode(['success' => false, 'error' => 'expired']);
        exit;
    }

    if (!empty($token['region_code']) && $storeRegion !== null) {
        if (strcasecmp($token['region_code'], $storeRegion) !== 0) {
            echo json_encode(['success' => false, 'error' => 'wrong_region']);
            exit;
        }
    }

    $constraints = $token['constraints_json']
        ? json_decode($token['constraints_json'], true)
        : [];

    if (isset($constraints['min_order_amount'])) {
        if ($orderAmount === null || $orderAmount < $constraints['min_order_amount']) {
            echo json_encode(['success' => false, 'error' => 'min_order_not_reached']);
            exit;
        }
    }

    $updated = $db_connect->update('qr_tokens', [
        'usage_count[+]'=> 1,
        'last_used_at'  => date('Y-m-d H:i:s'),
    ], [
        'id' => $token['id'],
        'usage_count[<]' => $token['usage_limit']
    ])->rowCount();

    if ($updated === 0) {
        echo json_encode(['success' => false, 'error' => 'usage_limit_reached']);
        exit;
    }

    echo json_encode([
        'success' => true,
        'token'   => [
            'code'        => $token['code'],
            'target_type' => $token['target_type'],
            'target_id'   => (int)$token['target_id'],
            'metadata'    => $token['metadata_json']
                ? json_decode($token['metadata_json'], true)
                : null,
        ]
    ]);
