WebOrbiton

Code

StocketBase

Self-hosted digital commerce, without commission fees or SaaS lock-in.

Version history

Version 1.1.0.0 2026-11-19

Browse files
Files changed39
Lines added+3755
Lines removed-492
account.php Modified +373 -157
⋮ 8 unchanged lines ⋮
  require_once __DIR__ . '/includes/language.php';
  require_once __DIR__ . '/includes/site-front.php';
  require_once __DIR__ . '/includes/currency.php';
+ require_once __DIR__ . '/includes/countries.php';
+ require_once __DIR__ . '/includes/orders.php';
+ require_once __DIR__ . '/includes/order-view.php';
+ require_once __DIR__ . '/includes/digital-files.php';
+ require_once __DIR__ . '/includes/licenses.php';
  
  UserAuth::boot();
  UserAuth::requireLogin();
  
  $reader = UserAuth::user();
  $settings = SiteFront::settings();
- $flashMessage = null;
+ $usersDb = Database::users();
+ $tabs = [
+     'overview' => Language::get('account_tab_overview', 'Overview'),
+     'orders' => Language::get('account_tab_orders', 'Orders'),
+     'downloads' => Language::get('account_tab_downloads', 'Downloads'),
+     'licenses' => Language::get('account_tab_licenses', 'License keys'),
+     'addresses' => Language::get('account_tab_addresses', 'Addresses'),
+     'profile' => Language::get('account_tab_profile', 'Profile'),
+     'privacy' => Language::get('account_tab_privacy', 'Privacy'),
+ ];
+ $activeTab = (string) ($_GET['tab'] ?? 'overview');
+ if (!isset($tabs[$activeTab])) {
+     $activeTab = 'overview';
+ }
  
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+     $postedTab = (string) ($_POST['tab'] ?? $activeTab);
      if (!Csrf::verify($_POST['csrf_token'] ?? null)) {
-         $flashMessage = Language::get('form_security_failed', 'Security check failed, please try again.');
-     } else {
-         $flashMessage = require __DIR__ . '/dashboard-actions/save-account.php';
-         $reader = UserAuth::user();
+         $_SESSION['account_flash'] = ['error', Language::get('form_security_failed', 'Security check failed, please try again.')];
+         header('Location: account.php?tab=' . urlencode(isset($tabs[$postedTab]) ? $postedTab : 'overview'));
+         exit;
      }
- }
  
- $subscriptionsStatement = Database::users()->prepare(
-     'SELECT * FROM subscriptions WHERE user_account_id = :id ORDER BY created_at DESC'
- );
- $subscriptionsStatement->execute(['id' => $reader['id']]);
- $subscriptions = $subscriptionsStatement->fetchAll();
+     if (($_POST['action'] ?? '') === 'export_data') {
+         $export = ['exported_at' => gmdate('c'), 'account' => array_diff_key($reader, array_flip(['password_hash']))];
+         $queries = [
+             'addresses' => 'SELECT * FROM user_addresses WHERE user_account_id = :id',
+             'orders' => 'SELECT * FROM orders WHERE user_account_id = :id',
+             'subscriptions' => 'SELECT * FROM subscriptions WHERE user_account_id = :id',
+             'consents' => 'SELECT consent_type, is_granted, granted_at, revoked_at FROM user_consents WHERE user_account_id = :id',
+             'reviews' => 'SELECT product_id, rating, body, created_at FROM product_reviews WHERE user_account_id = :id',
+         ];
+         foreach ($queries as $key => $sql) {
+             try {
+                 $statement = $usersDb->prepare($sql);
+                 $statement->execute(['id' => $reader['id']]);
+                 $export[$key] = $statement->fetchAll();
+             } catch (PDOException $exception) {
+                 $export[$key] = [];
+             }
+         }
+         foreach ($export['orders'] as $index => $exportedOrder) {
+             unset($export['orders'][$index]['access_token']);
+             $export['orders'][$index]['items'] = Orders::items((int) $exportedOrder['id']);
+         }
+         $export['license_keys'] = array_map(static fn(array $key): array => [
+             'product' => $key['product_title_snapshot'], 'key' => $key['license_key'], 'order' => $key['order_number'], 'assigned_at' => $key['assigned_at'],
+         ], Licenses::forUser((int) $reader['id']));
  
- $consentsStatement = Database::users()->prepare(
-     'SELECT consent_type, is_granted FROM user_consents WHERE user_account_id = :id'
- );
- $consentsStatement->execute(['id' => $reader['id']]);
- $consentRows = $consentsStatement->fetchAll();
- $consents = [];
- foreach ($consentRows as $row) {
-     $consents[$row['consent_type']] = (bool) $row['is_granted'];
+         header('Content-Type: application/json; charset=utf-8');
+         header('Content-Disposition: attachment; filename="my-data-' . date('Y-m-d') . '.json"');
+         header('Cache-Control: no-store');
+         echo json_encode($export, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+         exit;
+     }
+ 
+     $result = require __DIR__ . '/dashboard-actions/save-account.php';
+     if (is_array($result)) {
+         [$flashType, $flashText, $flashTab] = $result;
+         if ($flashType === 'deleted') {
+             header('Location: index.php');
+             exit;
+         }
+         $_SESSION['account_flash'] = [$flashType, $flashText];
+         header('Location: account.php?tab=' . urlencode((string) $flashTab));
+         exit;
+     }
+     header('Location: account.php?tab=' . urlencode($activeTab));
+     exit;
  }
  
- $ordersStatement = Database::users()->prepare(
-     'SELECT * FROM orders WHERE user_account_id = :id ORDER BY created_at DESC LIMIT 100'
- );
+ $flash = null;
+ if (isset($_SESSION['account_flash']) && is_array($_SESSION['account_flash'])) {
+     $flash = $_SESSION['account_flash'];
+     unset($_SESSION['account_flash']);
+ }
+ 
+ $ordersStatement = $usersDb->prepare("SELECT * FROM orders WHERE user_account_id = :id AND status <> 'failed' ORDER BY created_at DESC LIMIT 200");
  $ordersStatement->execute(['id' => $reader['id']]);
  $orders = $ordersStatement->fetchAll();
  
- require_once __DIR__ . '/includes/digital-files.php';
- 
  $accountDownloads = [];
  $ownedProductIds = DigitalFiles::ownedProductIds((int) $reader['id']);
  if (!empty($ownedProductIds)) {
      $placeholders = implode(',', array_fill(0, count($ownedProductIds), '?'));
-     $ownedProductsStatement = Database::site()->prepare("SELECT id, title FROM products WHERE id IN ({$placeholders})");
+     $ownedProductsStatement = Database::site()->prepare("SELECT id, title, slug, cover_image_path FROM products WHERE id IN ({$placeholders})");
      $ownedProductsStatement->execute($ownedProductIds);
-     $ownedTitles = array_column($ownedProductsStatement->fetchAll(), 'title', 'id');
+     $ownedProducts = [];
+     foreach ($ownedProductsStatement->fetchAll() as $ownedProduct) {
+         $ownedProducts[(int) $ownedProduct['id']] = $ownedProduct;
+     }
  
      foreach ($ownedProductIds as $ownedProductId) {
          $ownedFiles = DigitalFiles::filesForProduct($ownedProductId);
          if (empty($ownedFiles)) {
              continue;
          }
-         $ownedTitle = (string) ($ownedTitles[$ownedProductId] ?? ($ownedFiles[0]['product_title'] ?? ''));
-         $accountDownloads[] = ['title' => $ownedTitle !== '' ? $ownedTitle : $ownedFiles[0]['original_name'], 'files' => $ownedFiles];
+         $ownedProduct = $ownedProducts[$ownedProductId] ?? null;
+         $ownedTitle = (string) ($ownedProduct['title'] ?? ($ownedFiles[0]['product_title'] ?? ''));
+         $accountDownloads[] = [
+             'title' => $ownedTitle !== '' ? $ownedTitle : $ownedFiles[0]['original_name'],
+             'cover' => $ownedProduct['cover_image_path'] ?? null,
+             'files' => $ownedFiles,
+         ];
      }
      usort($accountDownloads, static fn(array $a, array $b): int => strcasecmp($a['title'], $b['title']));
  }
  
- $viewOrderId = (int) ($_GET['order'] ?? 0);
+ $licenseKeys = Licenses::forUser((int) $reader['id']);
+ 
+ $addressesStatement = $usersDb->prepare('SELECT * FROM user_addresses WHERE user_account_id = :id ORDER BY is_default_shipping DESC, id ASC');
+ $addressesStatement->execute(['id' => $reader['id']]);
+ $addresses = $addressesStatement->fetchAll();
+ 
+ $subscriptionsStatement = $usersDb->prepare('SELECT * FROM subscriptions WHERE user_account_id = :id ORDER BY created_at DESC');
+ $subscriptionsStatement->execute(['id' => $reader['id']]);
+ $subscriptions = $subscriptionsStatement->fetchAll();
+ 
+ $consentsStatement = $usersDb->prepare('SELECT consent_type, is_granted FROM user_consents WHERE user_account_id = :id ORDER BY id ASC');
+ $consentsStatement->execute(['id' => $reader['id']]);
+ $consents = [];
+ foreach ($consentsStatement->fetchAll() as $row) {
+     $consents[$row['consent_type']] = (bool) $row['is_granted'];
+ }
+ 
  $viewOrder = null;
- $viewOrderItems = [];
+ $viewOrderId = (int) ($_GET['order'] ?? 0);
  if ($viewOrderId > 0) {
-     $viewOrderStatement = Database::users()->prepare(
-         'SELECT * FROM orders WHERE id = :id AND user_account_id = :account_id LIMIT 1'
-     );
-     $viewOrderStatement->execute(['id' => $viewOrderId, 'account_id' => $reader['id']]);
-     $viewOrder = $viewOrderStatement->fetch();
+     foreach ($orders as $candidateOrder) {
+         if ((int) $candidateOrder['id'] === $viewOrderId) {
+             $viewOrder = Orders::ensureAccessToken($candidateOrder);
+             $activeTab = 'orders';
+         }
+     }
+ }
  
-     if ($viewOrder) {
-         $viewOrderItemsStatement = Database::users()->prepare(
-             'SELECT * FROM order_items WHERE order_id = :id ORDER BY id ASC'
-         );
-         $viewOrderItemsStatement->execute(['id' => $viewOrderId]);
-         $viewOrderItems = $viewOrderItemsStatement->fetchAll();
+ $editAddress = null;
+ $editAddressId = (int) ($_GET['edit'] ?? 0);
+ foreach ($addresses as $address) {
+     if ((int) $address['id'] === $editAddressId) {
+         $editAddress = $address;
      }
  }
  
- $pageTitle = Language::get('account_profile', 'Profile') . ' - ' . $settings['site_name'];
+ $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+ $pageTitle = Language::get('account_title', 'My account') . ' - ' . $settings['site_name'];
+ $pageNoindex = true;
  
  require __DIR__ . '/includes/front-header.php';
  
  ?>
- <h1 class="article-title"><?= htmlspecialchars(Language::get('account_profile', 'Profile')) ?></h1>
+ <div class="account-page">
+     <div class="account-head">
+         <div>
+             <h1 class="article-title"><?= $e(Language::get('account_title', 'My account')) ?></h1>
+             <p class="account-hello"><?= $e(str_replace('{name}', (string) ($reader['display_name'] ?: $reader['email']), Language::get('account_hello', 'Hi, {name}'))) ?></p>
+         </div>
+         <a class="account-logout" href="user-login.php?logout=1"><?= $e(Language::get('nav_logout', 'Log out')) ?></a>
+     </div>
  
- <?php if ($flashMessage !== null): ?>
- <p style="color: var(--accent);"><?= htmlspecialchars($flashMessage) ?></p>
- <?php endif; ?>
+     <nav class="account-tabs" aria-label="<?= $e(Language::get('account_title', 'My account')) ?>">
+         <?php foreach ($tabs as $tabKey => $tabLabel): ?>
+             <?php
+             $tabCount = match ($tabKey) {
+                 'orders' => count($orders),
+                 'downloads' => count($accountDownloads),
+                 'licenses' => count($licenseKeys),
+                 'addresses' => count($addresses),
+                 default => null,
+             };
+             ?>
+             <a href="account.php?tab=<?= $e($tabKey) ?>" class="<?= $activeTab === $tabKey ? 'active' : '' ?>" <?= $activeTab === $tabKey ? 'aria-current="page"' : '' ?>>
+                 <?= $e($tabLabel) ?><?php if ($tabCount): ?><span class="account-tab-count"><?= (int) $tabCount ?></span><?php endif; ?>
+             </a>
+         <?php endforeach; ?>
+     </nav>
  
- <form method="post" style="max-width:420px;margin-bottom:32px;">
- <?= Csrf::field() ?>
- <input type="hidden" name="action" value="update_profile">
- <label><?= htmlspecialchars(Language::get('auth_display_name', 'Display name')) ?></label>
- <input type="text" name="display_name" value="<?= htmlspecialchars($reader['display_name'] ?? '') ?>" style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--panel);color:var(--text);margin:6px 0 14px;">
- <label><?= htmlspecialchars(Language::get('account_current_password', 'Current password (required to set a new password)')) ?></label>
- <input type="password" name="current_password" autocomplete="current-password" style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--panel);color:var(--text);margin:6px 0 14px;">
- <label><?= htmlspecialchars(Language::get('account_new_password', 'New password (leave blank to keep current)')) ?></label>
- <input type="password" name="new_password" minlength="8" style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);background:var(--panel);color:var(--text);margin:6px 0 14px;">
- <button type="submit" class="unlock-btn" style="border:none;cursor:pointer;"><?= htmlspecialchars(Language::get('account_save', 'Save changes')) ?></button>
- </form>
+     <?php if ($flash !== null): ?>
+         <div class="account-flash account-flash-<?= $e($flash[0]) ?>" role="status"><?= $e($flash[1]) ?></div>
+     <?php endif; ?>
  
- <h2><?= htmlspecialchars(Language::get('account_orders', 'Order history')) ?></h2>
+     <?php if (empty($reader['email_verified_at'])): ?>
+         <div class="account-verify">
+             <p><?= $e(str_replace('{email}', (string) $reader['email'], Language::get('account_verify_notice', 'Please confirm your email address ({email}). After that, orders you placed as a guest with this email will show up here.'))) ?></p>
+             <form method="post">
+                 <?= Csrf::field() ?>
+                 <input type="hidden" name="action" value="resend_verification">
+                 <input type="hidden" name="tab" value="<?= $e($activeTab) ?>">
+                 <button type="submit" class="account-button-secondary"><?= $e(Language::get('account_verify_resend', 'Send the link again')) ?></button>
+             </form>
+         </div>
+     <?php endif; ?>
  
- <?php if ($viewOrder !== null): ?>
-     <p><a href="account.php">&larr; <?= htmlspecialchars(Language::get('account_back_to_orders', 'Back to order history')) ?></a></p>
-     <div class="order-summary">
-         <p><strong><?= htmlspecialchars(Language::get('order_number_label', 'Order number')) ?>:</strong> <?= htmlspecialchars($viewOrder['order_number']) ?></p>
-         <p><strong><?= htmlspecialchars(Language::get('order_status_label', 'Status')) ?>:</strong> <span class="status-pill status-<?= htmlspecialchars($viewOrder['status']) ?>"><?= htmlspecialchars(Language::get('order_status_' . $viewOrder['status'], ucfirst($viewOrder['status']))) ?></span></p>
-         <p><strong><?= htmlspecialchars(Language::get('order_placed_label', 'Placed on')) ?>:</strong> <?= htmlspecialchars($viewOrder['created_at']) ?></p>
-         <?php if (!empty($viewOrder['tracking_number'])): ?>
-             <p><strong><?= htmlspecialchars(Language::get('order_tracking_label', 'Tracking')) ?>:</strong>
-                 <?php if (!empty($viewOrder['tracking_url'])): ?>
-                     <a href="<?= htmlspecialchars($viewOrder['tracking_url']) ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($viewOrder['tracking_number']) ?></a>
-                 <?php else: ?>
-                     <?= htmlspecialchars($viewOrder['tracking_number']) ?>
-                 <?php endif; ?>
-             </p>
+     <?php if ($activeTab === 'overview'): ?>
+         <div class="account-cards">
+             <a class="account-card" href="account.php?tab=orders"><strong><?= count($orders) ?></strong><span><?= $e(Language::get('account_tab_orders', 'Orders')) ?></span></a>
+             <a class="account-card" href="account.php?tab=downloads"><strong><?= count($accountDownloads) ?></strong><span><?= $e(Language::get('account_tab_downloads', 'Downloads')) ?></span></a>
+             <a class="account-card" href="account.php?tab=licenses"><strong><?= count($licenseKeys) ?></strong><span><?= $e(Language::get('account_tab_licenses', 'License keys')) ?></span></a>
+             <a class="account-card" href="account.php?tab=addresses"><strong><?= count($addresses) ?></strong><span><?= $e(Language::get('account_tab_addresses', 'Addresses')) ?></span></a>
+         </div>
+ 
+         <h2 class="account-section-title"><?= $e(Language::get('account_recent_orders', 'Recent orders')) ?></h2>
+         <?php if (empty($orders)): ?>
+             <p class="account-empty"><?= $e(Language::get('account_no_orders', 'You have not placed any orders yet.')) ?> <a href="index.php"><?= $e(Language::get('order_confirmation_continue_shopping', 'Continue shopping')) ?></a></p>
+         <?php else: ?>
+             <?php $recentOrders = array_slice($orders, 0, 3); ?>
+             <?php require __DIR__ . '/includes/account-order-list.php'; ?>
          <?php endif; ?>
  
-         <table class="dash-table">
-             <thead>
-                 <tr>
-                     <th><?= htmlspecialchars(Language::get('cart_column_product', 'Product')) ?></th>
-                     <th><?= htmlspecialchars(Language::get('cart_column_quantity', 'Quantity')) ?></th>
-                     <th><?= htmlspecialchars(Language::get('cart_column_total', 'Total')) ?></th>
-                 </tr>
-             </thead>
-             <tbody>
-                 <?php foreach ($viewOrderItems as $orderItem): ?>
-                     <tr>
-                         <td><?= htmlspecialchars($orderItem['product_title_snapshot']) ?><?= $orderItem['variant_name_snapshot'] !== null ? ' — ' . htmlspecialchars($orderItem['variant_name_snapshot']) : '' ?></td>
-                         <td><?= (int) $orderItem['quantity'] ?></td>
-                         <td><?= htmlspecialchars(Currency::format((int) $orderItem['total_cents'], $viewOrder['currency'])) ?></td>
-                     </tr>
+         <?php if (($settings['pricing_model'] ?? 'per_product') === 'subscription' || !empty($subscriptions)): ?>
+             <h2 class="account-section-title"><?= $e(Language::get('account_subscriptions', 'Subscriptions')) ?></h2>
+             <?php if (empty($subscriptions)): ?>
+                 <p class="account-empty"><?= $e(Language::get('account_no_subscriptions', 'No active subscriptions.')) ?></p>
+             <?php else: ?>
+                 <ul class="account-subscriptions">
+                     <?php foreach ($subscriptions as $subscription): ?>
+                         <li>
+                             <span><?= $e(ucfirst((string) $subscription['provider'])) ?><?= !empty($subscription['plan_code']) ? ' · ' . $e($subscription['plan_code']) : '' ?></span>
+                             <span class="status-pill status-<?= $e($subscription['status']) ?>"><?= $e(Language::get('subscription_status_' . $subscription['status'], (string) $subscription['status'])) ?></span>
+                             <?php if (!empty($subscription['current_period_end'])): ?><small><?= $e(str_replace('{date}', OrderView::date((string) $subscription['current_period_end']), Language::get('account_subscription_until', 'until {date}'))) ?></small><?php endif; ?>
+                         </li>
+                     <?php endforeach; ?>
+                 </ul>
+             <?php endif; ?>
+         <?php endif; ?>
+     <?php endif; ?>
+ 
+     <?php if ($activeTab === 'orders'): ?>
+         <?php if ($viewOrder !== null): ?>
+             <p><a href="account.php?tab=orders">&larr; <?= $e(Language::get('account_back_to_orders', 'Back to order history')) ?></a></p>
+             <?= OrderView::render($viewOrder, Orders::items((int) $viewOrder['id']), true) ?>
+             <?= OrderView::copyScript() ?>
+         <?php elseif (empty($orders)): ?>
+             <p class="account-empty"><?= $e(Language::get('account_no_orders', 'You have not placed any orders yet.')) ?></p>
+         <?php else: ?>
+             <?php $recentOrders = $orders; ?>
+             <?php require __DIR__ . '/includes/account-order-list.php'; ?>
+         <?php endif; ?>
+     <?php endif; ?>
+ 
+     <?php if ($activeTab === 'downloads'): ?>
+         <?php if (empty($accountDownloads)): ?>
+             <p class="account-empty"><?= $e(Language::get('account_no_downloads', 'Files you buy will show up here.')) ?></p>
+         <?php else: ?>
+             <p class="account-hint"><?= $e(Language::get('order_downloads_unlimited', 'No limit while you are logged in.')) ?></p>
+             <div class="account-downloads">
+                 <?php foreach ($accountDownloads as $accountDownload): ?>
+                     <div class="download-group">
+                         <h3><?= $e($accountDownload['title']) ?></h3>
+                         <ul class="download-list">
+                             <?php foreach ($accountDownload['files'] as $accountFile): ?>
+                                 <li>
+                                     <a href="<?= $e(DigitalFiles::downloadUrl((int) $accountFile['id'])) ?>" rel="nofollow"><?= Icons::icon('download', 'icon icon-sm') ?><?= $e(DigitalFiles::displayName($accountFile)) ?></a>
+                                     <small><?= $e(DigitalFiles::formatSize((int) $accountFile['size_bytes'])) ?><?= !empty($accountFile['created_at']) ? ' · ' . $e(str_replace('{date}', OrderView::date((string) $accountFile['created_at']), Language::get('account_file_updated', 'updated {date}'))) : '' ?></small>
+                                 </li>
+                             <?php endforeach; ?>
+                         </ul>
+                     </div>
                  <?php endforeach; ?>
-             </tbody>
-         </table>
+             </div>
+         <?php endif; ?>
+     <?php endif; ?>
  
-         <div class="cart-summary">
-             <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_subtotal', 'Subtotal')) ?></span><span><?= htmlspecialchars(Currency::format((int) $viewOrder['subtotal_cents'], $viewOrder['currency'])) ?></span></div>
-             <?php if ((int) $viewOrder['discount_cents'] > 0): ?>
-                 <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_discount', 'Discount')) ?></span><span>-<?= htmlspecialchars(Currency::format((int) $viewOrder['discount_cents'], $viewOrder['currency'])) ?></span></div>
-             <?php endif; ?>
-             <div class="cart-summary-row cart-summary-total"><span><?= htmlspecialchars(Language::get('cart_total', 'Total')) ?></span><span><?= htmlspecialchars(Currency::format((int) $viewOrder['total_cents'], $viewOrder['currency'])) ?></span></div>
-         </div>
-     </div>
- <?php else: ?>
-     <table class="dash-table">
-         <thead>
-             <tr>
-                 <th><?= htmlspecialchars(Language::get('order_number_label', 'Order number')) ?></th>
-                 <th><?= htmlspecialchars(Language::get('order_placed_label', 'Placed on')) ?></th>
-                 <th><?= htmlspecialchars(Language::get('order_status_label', 'Status')) ?></th>
-                 <th><?= htmlspecialchars(Language::get('cart_column_total', 'Total')) ?></th>
-                 <th></th>
-             </tr>
-         </thead>
-         <tbody>
-             <?php foreach ($orders as $orderRow): ?>
-                 <tr>
-                     <td><?= htmlspecialchars($orderRow['order_number']) ?></td>
-                     <td><?= htmlspecialchars($orderRow['created_at']) ?></td>
-                     <td><span class="status-pill status-<?= htmlspecialchars($orderRow['status']) ?>"><?= htmlspecialchars(Language::get('order_status_' . $orderRow['status'], ucfirst($orderRow['status']))) ?></span></td>
-                     <td><?= htmlspecialchars(Currency::format((int) $orderRow['total_cents'], $orderRow['currency'])) ?></td>
-                     <td><a href="account.php?order=<?= (int) $orderRow['id'] ?>"><?= htmlspecialchars(Language::get('order_view_button', 'View')) ?></a></td>
-                 </tr>
-             <?php endforeach; ?>
-             <?php if (empty($orders)): ?>
-                 <tr><td colspan="5"><?= htmlspecialchars(Language::get('account_no_orders', 'You have not placed any orders yet.')) ?></td></tr>
-             <?php endif; ?>
-         </tbody>
-     </table>
- <?php endif; ?>
+     <?php if ($activeTab === 'licenses'): ?>
+         <?php if (empty($licenseKeys)): ?>
+             <p class="account-empty"><?= $e(Language::get('account_no_licenses', 'License keys for software you buy will show up here.')) ?></p>
+         <?php else: ?>
+             <ul class="license-list">
+                 <?php foreach ($licenseKeys as $licenseKey): ?>
+                     <li>
+                         <span><?= $e($licenseKey['product_title_snapshot']) ?><small><a href="account.php?tab=orders&amp;order=<?= (int) $licenseKey['order_ref'] ?>"><?= $e($licenseKey['order_number']) ?></a></small></span>
+                         <code class="license-key"><?= $e($licenseKey['license_key']) ?></code>
+                         <button type="button" class="license-copy" data-copy="<?= $e($licenseKey['license_key']) ?>" data-copied="<?= $e(Language::get('code_copied', 'Copied')) ?>"><?= $e(Language::get('code_copy', 'Copy')) ?></button>
+                     </li>
+                 <?php endforeach; ?>
+             </ul>
+             <?= OrderView::copyScript() ?>
+         <?php endif; ?>
+     <?php endif; ?>
  
- <?php if (!empty($accountDownloads)): ?>
- <h2><?= htmlspecialchars(Language::get('account_downloads', 'Downloads')) ?></h2>
- <?php foreach ($accountDownloads as $accountDownload): ?>
- <h3 style="margin:18px 0 0;font-size:15px;"><?= htmlspecialchars($accountDownload['title']) ?></h3>
- <ul class="download-list">
- <?php foreach ($accountDownload['files'] as $accountFile): ?>
- <li>
- <a href="<?= htmlspecialchars(DigitalFiles::downloadUrl((int) $accountFile['id'])) ?>" rel="nofollow"><?= Icons::icon('download', 'icon icon-sm') ?><?= htmlspecialchars(DigitalFiles::displayName($accountFile)) ?></a>
- <small><?= htmlspecialchars(DigitalFiles::formatSize((int) $accountFile['size_bytes'])) ?></small>
- </li>
- <?php endforeach; ?>
- </ul>
- <?php endforeach; ?>
- <?php endif; ?>
+     <?php if ($activeTab === 'addresses'): ?>
+         <?php if (!empty($addresses)): ?>
+             <div class="account-addresses">
+                 <?php foreach ($addresses as $address): ?>
+                     <div class="account-address">
+                         <?php if (!empty($address['label'])): ?><strong class="account-address-label"><?= $e($address['label']) ?></strong><?php endif; ?>
+                         <p>
+                             <?= $e($address['full_name']) ?><br>
+                             <?php if (!empty($address['company'])): ?><?= $e($address['company']) ?><br><?php endif; ?>
+                             <?= $e($address['address_line1']) ?><br>
+                             <?php if (!empty($address['address_line2'])): ?><?= $e($address['address_line2']) ?><br><?php endif; ?>
+                             <?= $e(trim($address['postal_code'] . ' ' . $address['city'])) ?><br>
+                             <?= $e(Countries::name((string) $address['country'])) ?>
+                             <?php if (!empty($address['phone'])): ?><br><?= $e($address['phone']) ?><?php endif; ?>
+                             <?php if (!empty($address['tax_id'])): ?><br><?= $e(Language::get('receipt_tax_id', 'Tax ID')) ?>: <?= $e($address['tax_id']) ?><?php endif; ?>
+                         </p>
+                         <div class="account-address-badges">
+                             <?php if ((int) $address['is_default_shipping'] === 1): ?><span class="account-badge"><?= $e(Language::get('account_default_shipping', 'Default for delivery')) ?></span><?php endif; ?>
+                             <?php if ((int) $address['is_default_billing'] === 1): ?><span class="account-badge"><?= $e(Language::get('account_default_billing', 'Default for billing')) ?></span><?php endif; ?>
+                         </div>
+                         <div class="account-address-actions">
+                             <a href="account.php?tab=addresses&amp;edit=<?= (int) $address['id'] ?>#address-form"><?= $e(Language::get('account_edit', 'Edit')) ?></a>
+                             <?php if ((int) $address['is_default_shipping'] !== 1): ?>
+                                 <form method="post"><?= Csrf::field() ?><input type="hidden" name="action" value="default_address"><input type="hidden" name="kind" value="shipping"><input type="hidden" name="address_id" value="<?= (int) $address['id'] ?>"><button type="submit"><?= $e(Language::get('account_make_default_shipping', 'Use for delivery')) ?></button></form>
+                             <?php endif; ?>
+                             <?php if ((int) $address['is_default_billing'] !== 1): ?>
+                                 <form method="post"><?= Csrf::field() ?><input type="hidden" name="action" value="default_address"><input type="hidden" name="kind" value="billing"><input type="hidden" name="address_id" value="<?= (int) $address['id'] ?>"><button type="submit"><?= $e(Language::get('account_make_default_billing', 'Use for billing')) ?></button></form>
+                             <?php endif; ?>
+                             <form method="post" onsubmit="return confirm(<?= $e(json_encode(Language::get('account_address_delete_confirm', 'Delete this address?'))) ?>);"><?= Csrf::field() ?><input type="hidden" name="action" value="delete_address"><input type="hidden" name="address_id" value="<?= (int) $address['id'] ?>"><button type="submit" class="account-danger-link"><?= $e(Language::get('account_delete', 'Delete')) ?></button></form>
+                         </div>
+                     </div>
+                 <?php endforeach; ?>
+             </div>
+         <?php endif; ?>
  
- <?php if (($settings['pricing_model'] ?? 'per_product') === 'subscription' || !empty($subscriptions)): ?>
- <h2><?= htmlspecialchars(Language::get('account_subscriptions', 'Subscriptions')) ?></h2>
- <ul>
- <?php foreach ($subscriptions as $subscription): ?>
- <li><?= htmlspecialchars($subscription['provider']) ?> — <?= htmlspecialchars($subscription['plan_code'] ?? '') ?> (<?= htmlspecialchars(Language::get('subscription_status_' . $subscription['status'], $subscription['status'])) ?>)</li>
- <?php endforeach; ?>
- <?php if (empty($subscriptions)): ?>
- <li><?= htmlspecialchars(Language::get('account_no_subscriptions', 'No active subscriptions.')) ?></li>
- <?php endif; ?>
- </ul>
- <?php endif; ?>
+         <form method="post" class="account-form" id="address-form">
+             <h2 class="account-section-title"><?= $e($editAddress !== null ? Language::get('account_edit_address', 'Edit address') : Language::get('account_add_address', 'Add an address')) ?></h2>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="save_address">
+             <input type="hidden" name="address_id" value="<?= (int) ($editAddress['id'] ?? 0) ?>">
+             <label><?= $e(Language::get('account_address_label', 'Name for this address (optional, e.g. Home or Office)')) ?><input type="text" name="label" maxlength="60" value="<?= $e($editAddress['label'] ?? '') ?>"></label>
+             <label><?= $e(Language::get('checkout_full_name', 'Full name')) ?><input type="text" name="full_name" required maxlength="190" autocomplete="name" value="<?= $e($editAddress['full_name'] ?? ($reader['display_name'] ?? '')) ?>"></label>
+             <div class="checkout-grid">
+                 <label><?= $e(Language::get('checkout_company', 'Company name')) ?><input type="text" name="company" maxlength="190" autocomplete="organization" value="<?= $e($editAddress['company'] ?? '') ?>"></label>
+                 <label><?= $e(Language::get('checkout_tax_id', 'Tax ID (VAT number)')) ?><input type="text" name="tax_id" maxlength="60" value="<?= $e($editAddress['tax_id'] ?? '') ?>"></label>
+             </div>
+             <label><?= $e(Language::get('checkout_country_label', 'Country')) ?>
+                 <select name="country" required autocomplete="country">
+                     <option value=""><?= $e(Language::get('checkout_choose_country', 'Choose a country')) ?></option>
+                     <?php foreach (Countries::all() as $countryCode => $countryName): ?>
+                         <option value="<?= $e($countryCode) ?>" <?= ($editAddress['country'] ?? Shop::setting('shop_default_country', '')) === $countryCode ? 'selected' : '' ?>><?= $e($countryName) ?></option>
+                     <?php endforeach; ?>
+                 </select>
+             </label>
+             <label><?= $e(Language::get('checkout_address_line1', 'Address')) ?><input type="text" name="address_line1" required maxlength="255" autocomplete="address-line1" value="<?= $e($editAddress['address_line1'] ?? '') ?>"></label>
+             <label><?= $e(Language::get('checkout_address_line2', 'Address line 2 (optional)')) ?><input type="text" name="address_line2" maxlength="255" autocomplete="address-line2" value="<?= $e($editAddress['address_line2'] ?? '') ?>"></label>
+             <div class="checkout-grid">
+                 <label><?= $e(Language::get('checkout_postal_code', 'Postal code')) ?><input type="text" name="postal_code" required maxlength="30" autocomplete="postal-code" value="<?= $e($editAddress['postal_code'] ?? '') ?>"></label>
+                 <label><?= $e(Language::get('checkout_city', 'City')) ?><input type="text" name="city" required maxlength="120" autocomplete="address-level2" value="<?= $e($editAddress['city'] ?? '') ?>"></label>
+             </div>
+             <div class="checkout-grid">
+                 <label><?= $e(Language::get('checkout_region', 'State / Region')) ?><input type="text" name="region" maxlength="120" autocomplete="address-level1" value="<?= $e($editAddress['region'] ?? '') ?>"></label>
+                 <label><?= $e(Language::get('checkout_phone', 'Phone number')) ?><input type="tel" name="phone" maxlength="40" autocomplete="tel" value="<?= $e($editAddress['phone'] ?? ($reader['phone'] ?? '')) ?>"></label>
+             </div>
+             <div class="account-form-actions">
+                 <button type="submit" class="unlock-btn"><?= $e(Language::get('account_save', 'Save changes')) ?></button>
+                 <?php if ($editAddress !== null): ?><a href="account.php?tab=addresses"><?= $e(Language::get('account_cancel', 'Cancel')) ?></a><?php endif; ?>
+             </div>
+         </form>
+     <?php endif; ?>
  
- <h2><?= htmlspecialchars(Language::get('account_consents', 'Privacy consents')) ?></h2>
- <form method="post" style="max-width:420px;">
- <?= Csrf::field() ?>
- <input type="hidden" name="action" value="update_consents">
- <label><input type="checkbox" name="consent_analytics" <?= !empty($consents['analytics']) ? 'checked' : '' ?>> <?= htmlspecialchars(Language::get('account_consent_analytics', 'Allow analytics tracking')) ?></label>
- <label><input type="checkbox" name="consent_ads_personalization" <?= !empty($consents['ads_personalization']) ? 'checked' : '' ?>> <?= htmlspecialchars(Language::get('account_consent_ads', 'Allow personalized ads')) ?></label>
- <button type="submit" class="unlock-btn" style="border:none;cursor:pointer;margin-top:14px;"><?= htmlspecialchars(Language::get('account_save', 'Save changes')) ?></button>
- </form>
+     <?php if ($activeTab === 'profile'): ?>
+         <form method="post" class="account-form">
+             <h2 class="account-section-title"><?= $e(Language::get('account_details', 'Your details')) ?></h2>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="update_profile">
+             <label><?= $e(Language::get('auth_display_name', 'Display name')) ?><input type="text" name="display_name" maxlength="100" value="<?= $e($reader['display_name'] ?? '') ?>"></label>
+             <label><?= $e(Language::get('checkout_phone', 'Phone number')) ?><input type="tel" name="phone" maxlength="40" autocomplete="tel" value="<?= $e($reader['phone'] ?? '') ?>"></label>
+             <label class="checkout-check"><input type="checkbox" name="marketing_opt_in" value="1" <?= (int) ($reader['marketing_opt_in'] ?? 0) === 1 ? 'checked' : '' ?>> <?= $e(Language::get('account_marketing', 'Send me news and offers by email')) ?></label>
+             <div class="account-form-actions"><button type="submit" class="unlock-btn"><?= $e(Language::get('account_save', 'Save changes')) ?></button></div>
+         </form>
+ 
+         <form method="post" class="account-form">
+             <h2 class="account-section-title"><?= $e(Language::get('account_email_title', 'Email address')) ?></h2>
+             <p class="account-hint"><?= $e(Language::get('account_email_current', 'Current email:')) ?> <strong><?= $e($reader['email']) ?></strong>
+                 <?= !empty($reader['email_verified_at']) ? '<span class="account-badge">' . $e(Language::get('account_email_verified', 'confirmed')) . '</span>' : '' ?></p>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="change_email">
+             <label><?= $e(Language::get('account_new_email', 'New email address')) ?><input type="email" name="new_email" required maxlength="190" autocomplete="email"></label>
+             <label><?= $e(Language::get('account_current_password_short', 'Current password')) ?><input type="password" name="current_password" required autocomplete="current-password"></label>
+             <div class="account-form-actions"><button type="submit" class="account-button-secondary"><?= $e(Language::get('account_change_email', 'Change email')) ?></button></div>
+         </form>
+ 
+         <form method="post" class="account-form">
+             <h2 class="account-section-title"><?= $e(Language::get('account_password_title', 'Password')) ?></h2>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="change_password">
+             <label><?= $e(Language::get('account_current_password_short', 'Current password')) ?><input type="password" name="current_password" required autocomplete="current-password"></label>
+             <div class="checkout-grid">
+                 <label><?= $e(Language::get('account_new_password_short', 'New password')) ?><input type="password" name="new_password" required minlength="8" autocomplete="new-password"></label>
+                 <label><?= $e(Language::get('auth_confirm_password', 'Confirm password')) ?><input type="password" name="new_password_confirm" required minlength="8" autocomplete="new-password"></label>
+             </div>
+             <div class="account-form-actions"><button type="submit" class="account-button-secondary"><?= $e(Language::get('account_change_password', 'Change password')) ?></button></div>
+         </form>
+     <?php endif; ?>
+ 
+     <?php if ($activeTab === 'privacy'): ?>
+         <form method="post" class="account-form">
+             <h2 class="account-section-title"><?= $e(Language::get('account_consents', 'Privacy consents')) ?></h2>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="update_consents">
+             <label class="checkout-check"><input type="checkbox" name="consent_analytics" <?= !empty($consents['analytics']) ? 'checked' : '' ?>> <?= $e(Language::get('account_consent_analytics', 'Allow analytics tracking')) ?></label>
+             <label class="checkout-check"><input type="checkbox" name="consent_ads_personalization" <?= !empty($consents['ads_personalization']) ? 'checked' : '' ?>> <?= $e(Language::get('account_consent_ads', 'Allow personalized ads')) ?></label>
+             <div class="account-form-actions"><button type="submit" class="unlock-btn"><?= $e(Language::get('account_save', 'Save changes')) ?></button></div>
+         </form>
+ 
+         <form method="post" class="account-form">
+             <h2 class="account-section-title"><?= $e(Language::get('account_export_title', 'Download your data')) ?></h2>
+             <p class="account-hint"><?= $e(Language::get('account_export_hint', 'Get a file with your account details, addresses, orders and license keys.')) ?></p>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="export_data">
+             <div class="account-form-actions"><button type="submit" class="account-button-secondary"><?= Icons::icon('download', 'icon icon-sm') ?><?= $e(Language::get('account_export_button', 'Download my data')) ?></button></div>
+         </form>
+ 
+         <form method="post" class="account-form account-danger-zone" onsubmit="return confirm(<?= $e(json_encode(Language::get('account_delete_confirm', 'Delete your account for good? This cannot be undone.'))) ?>);">
+             <h2 class="account-section-title"><?= $e(Language::get('account_delete_title', 'Delete account')) ?></h2>
+             <p class="account-hint"><?= $e(Language::get('account_delete_hint', 'We remove your personal details and log you out. Orders stay in our records because the law requires it, but they are no longer linked to a login.')) ?></p>
+             <?= Csrf::field() ?>
+             <input type="hidden" name="action" value="delete_account">
+             <label><?= $e(Language::get('account_current_password_short', 'Current password')) ?><input type="password" name="current_password" required autocomplete="current-password"></label>
+             <label class="checkout-check"><input type="checkbox" name="confirm_delete" value="1" required> <?= $e(Language::get('account_delete_check', 'I understand that this cannot be undone')) ?></label>
+             <div class="account-form-actions"><button type="submit" class="account-button-danger"><?= $e(Language::get('account_delete_button', 'Delete my account')) ?></button></div>
+         </form>
+     <?php endif; ?>
+ </div>
  
  <?php require __DIR__ . '/includes/front-footer.php'; ?>
  
assets/dashboard.css Modified

Not shown (binary file or too large to diff).

assets/site.css Modified

Not shown (binary file or too large to diff).

cart.php Modified +27 -2
⋮ 235 unchanged lines ⋮
          <?php if ($discountCents > 0): ?>
              <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_discount', 'Discount')) ?></span><span>-<?= htmlspecialchars(Currency::format($discountCents, $cartCurrency)) ?></span></div>
          <?php endif; ?>
-         <div class="cart-summary-row cart-summary-total"><span><?= htmlspecialchars(Language::get('cart_total', 'Total')) ?></span><span><?= htmlspecialchars(Currency::format($totalCents, $cartCurrency)) ?></span></div>
-         <p class="cart-tax-note"><?= htmlspecialchars(Language::get('cart_tax_note', 'Tax is calculated at checkout where required.')) ?></p>
+         <?php
+         require_once __DIR__ . '/includes/shop.php';
+         $cartNeedsShipping = Cart::requiresShipping();
+         $freeShippingFrom = null;
+         if ($cartNeedsShipping) {
+             foreach (Shop::shippingMethods() as $cartMethod) {
+                 if ($cartMethod['free_over_cents'] !== null && ($freeShippingFrom === null || $cartMethod['free_over_cents'] < $freeShippingFrom)) {
+                     $freeShippingFrom = (int) $cartMethod['free_over_cents'];
+                 }
+             }
+         }
+         ?>
+         <div class="cart-summary-row cart-summary-total"><span><?= htmlspecialchars($cartNeedsShipping && !empty(Shop::shippingMethods()) ? Language::get('cart_total_before_delivery', 'Total without delivery') : Language::get('cart_total', 'Total')) ?></span><span><?= htmlspecialchars(Currency::format($totalCents, $cartCurrency)) ?></span></div>
+         <?php if ($freeShippingFrom !== null): ?>
+             <?php $missingForFree = $freeShippingFrom - $totalCents; ?>
+             <p class="cart-free-shipping<?= $missingForFree <= 0 ? ' is-reached' : '' ?>">
+                 <?= htmlspecialchars($missingForFree <= 0
+                     ? Language::get('cart_free_shipping_reached', 'You get free delivery.')
+                     : str_replace('{amount}', Currency::format($missingForFree, $cartCurrency), Language::get('cart_free_shipping_missing', 'Add {amount} more for free delivery.'))) ?>
+             </p>
+             <?php if ($missingForFree > 0): ?>
+                 <div class="cart-free-shipping-bar"><span style="width:<?= (int) max(4, min(100, round($totalCents / max(1, $freeShippingFrom) * 100))) ?>%"></span></div>
+             <?php endif; ?>
+         <?php endif; ?>
+         <p class="cart-tax-note"><?= htmlspecialchars(Shop::taxEnabled()
+             ? (Shop::pricesIncludeTax() ? str_replace('{tax}', Shop::taxLabel(), Language::get('cart_tax_included_note', 'Prices include {tax}. Delivery is added at checkout.')) : str_replace('{tax}', Shop::taxLabel(), Language::get('cart_tax_added_note', '{tax} and delivery are added at checkout.')))
+             : Language::get('cart_delivery_note', 'Delivery options and costs are shown at checkout.')) ?></p>
      </div>
  
      <a href="checkout.php" class="unlock-btn"><?= htmlspecialchars(Language::get('cart_checkout_button', 'Proceed to checkout')) ?></a>
⋮ 4 unchanged lines ⋮
checkout.php Modified

Not shown (binary file or too large to diff).

dashboard-actions/order-tools.php Added +41 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ if (count(get_included_files()) === 1) {
+     http_response_code(403);
+     exit;
+ }
+ 
+ if (!Auth::hasRoleAtLeast(Auth::ROLE_STORE_MANAGER)) {
+     return ['You don\'t have access to orders.', 'error', null];
+ }
+ 
+ require_once __DIR__ . '/../includes/orders.php';
+ 
+ $orderId = (int) ($_POST['order_id'] ?? 0);
+ $tool = (string) ($_POST['tool'] ?? '');
+ $order = Orders::find($orderId);
+ 
+ if ($order === null) {
+     return ['We couldn\'t find that order.', 'error', null];
+ }
+ 
+ if ($tool === 'resend') {
+     if (!Orders::resendConfirmation($orderId)) {
+         return ['The email didn\'t go out. Check the email settings and that the order is paid.', 'error', $orderId];
+     }
+     Orders::addHistory($orderId, (string) $order['status'], 'Confirmation sent again', (int) $currentUser['id']);
+ 
+     return ['Confirmation sent again.', 'success', $orderId];
+ }
+ 
+ if ($tool === 'reset_downloads') {
+     $count = DigitalFiles::resetGrantsForOrder($orderId);
+     Orders::addHistory($orderId, (string) $order['status'], 'Download limits reset', (int) $currentUser['id']);
+ 
+     return [$count > 0 ? 'Download limits reset. The links work again.' : 'There were no download links to reset.', 'success', $orderId];
+ }
+ 
+ return ['Unknown action.', 'error', $orderId];
+ 
dashboard-actions/product-licenses.php Added +49 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ if (count(get_included_files()) === 1) {
+     http_response_code(403);
+     exit;
+ }
+ 
+ require_once __DIR__ . '/../includes/licenses.php';
+ 
+ if (!Auth::hasRoleAtLeast(Auth::ROLE_STORE_MANAGER)) {
+     return ['You don\'t have access to license keys.', 'error', null];
+ }
+ 
+ $productId = (int) ($_POST['product_id'] ?? 0);
+ $productStatement = Database::site()->prepare('SELECT id FROM products WHERE id = :id AND deleted_at IS NULL LIMIT 1');
+ $productStatement->execute(['id' => $productId]);
+ if (!$productStatement->fetch()) {
+     return ['We couldn\'t find that product.', 'error', null];
+ }
+ 
+ $tool = (string) ($_POST['license_tool'] ?? 'save');
+ 
+ if ($tool === 'delete_key') {
+     $deleted = Licenses::deleteUnused($productId, (int) ($_POST['key_id'] ?? 0));
+ 
+     return [$deleted ? 'Key removed.' : 'Only keys that were not sent to anyone can be removed.', $deleted ? 'success' : 'error', $productId];
+ }
+ 
+ $mode = in_array($_POST['license_mode'] ?? 'none', Licenses::MODES, true) ? (string) $_POST['license_mode'] : 'none';
+ $rawPattern = trim((string) ($_POST['license_pattern'] ?? ''));
+ $pattern = Licenses::sanitizePattern($rawPattern);
+ if ($mode === 'generate' && $rawPattern !== '' && $pattern === '') {
+     return ['The key pattern needs at least 8 X (letters) or # (digits), like XXXX-XXXX-XXXX.', 'error', $productId];
+ }
+ 
+ Database::site()->prepare('UPDATE products SET license_mode = :mode, license_pattern = :pattern WHERE id = :id')
+     ->execute(['mode' => $mode, 'pattern' => $pattern !== '' ? $pattern : null, 'id' => $productId]);
+ 
+ $message = 'License settings saved.';
+ $newKeys = (string) ($_POST['license_keys'] ?? '');
+ if (trim($newKeys) !== '') {
+     [$added, $skipped] = Licenses::addToPool($productId, $newKeys);
+     $message .= ' Added ' . $added . ' key' . ($added === 1 ? '' : 's') . ($skipped > 0 ? ', skipped ' . $skipped . ' that were already there or too long' : '') . '.';
+ }
+ 
+ return [$message, 'success', $productId];
+ 
dashboard-actions/refund-order.php Modified +12 -10
⋮ 28 unchanged lines ⋮
      return ['This order was already refunded.', 'error', $orderId];
  }
  
- if (empty($order['provider_payment_id'])) {
+ require_once __DIR__ . '/../includes/orders.php';
+ 
+ if (!in_array($order['status'], Orders::PAID_STATUSES, true)) {
      return ['This order hasn\'t been paid, so there\'s nothing to refund.', 'error', null];
  }
  
  $refunded = false;
+ $manualRefund = in_array((string) ($order['payment_method'] ?? ''), ['bank_transfer', 'cod', 'free'], true)
+     || in_array((string) $order['provider'], ['manual', 'free'], true);
  
- if ($order['provider'] === 'stripe' && is_file(__DIR__ . '/../includes/payments/stripe-client.php')) {
+ if ($manualRefund) {
+     $refunded = true;
+ } elseif (empty($order['provider_payment_id'])) {
+     return ['This order has no payment reference, so it can\'t be refunded automatically. Refund it at the payment company and set the status to Refunded.', 'error', $orderId];
+ } elseif ($order['provider'] === 'stripe' && is_file(__DIR__ . '/../includes/payments/stripe-client.php')) {
      require_once __DIR__ . '/../includes/payments/stripe-client.php';
      if (class_exists('StripeClient')) {
          $refunded = (new StripeClient())->createRefund((string) $order['provider_payment_id']);
⋮ 6 unchanged lines ⋮
      return ['The payment company didn\'t accept the refund, so nothing changed. Please try again or refund it from their site.', 'error', null];
  }
  
- $usersDb->prepare("UPDATE orders SET status = 'refunded', updated_at = NOW() WHERE id = :id")->execute(['id' => $orderId]);
- 
- require_once __DIR__ . '/../includes/digital-files.php';
- DigitalFiles::revokeGrantsForOrder($orderId);
- $usersDb->prepare(
-     "INSERT INTO order_status_history (order_id, status, note, changed_by_team_account_id) VALUES (:id, 'refunded', 'Refunded by staff', :account_id)"
- )->execute(['id' => $orderId, 'account_id' => $currentUser['id']]);
+ Orders::close($orderId, 'refunded', 'Refunded by staff', (int) $currentUser['id'], isset($_POST['restock']));
  
- return ['Refund done. The money is on its way back to the customer.', 'success', $orderId];
+ return [$manualRefund ? 'Marked as refunded. Remember to send the money back to the customer yourself.' : 'Refund done. The money is on its way back to the customer.', 'success', $orderId];
  
dashboard-actions/save-account.php Modified +178 -32
⋮ 6 unchanged lines ⋮
      exit;
  }
  
- $action = $_POST['action'] ?? '';
+ require_once __DIR__ . '/../includes/countries.php';
+ require_once __DIR__ . '/../includes/account-emails.php';
+ 
+ $action = (string) ($_POST['action'] ?? '');
  $reader = UserAuth::user();
+ $usersDb = Database::users();
+ $accountText = static function (string $key, int $max): string {
+     $value = trim((string) preg_replace('/[\x00-\x1F\x7F]+/u', ' ', (string) ($_POST[$key] ?? '')));
  
+     return mb_substr($value, 0, $max);
+ };
+ 
  if ($action === 'update_profile') {
-     $displayName = mb_substr(trim((string) ($_POST['display_name'] ?? '')), 0, 100);
+     $displayName = $accountText('display_name', 100);
+     $phone = $accountText('phone', 40);
+     $usersDb->prepare('UPDATE user_accounts SET display_name = :display_name, phone = :phone, marketing_opt_in = :marketing WHERE id = :id')
+         ->execute([
+             'display_name' => $displayName !== '' ? $displayName : $reader['display_name'],
+             'phone' => $phone !== '' ? $phone : null,
+             'marketing' => isset($_POST['marketing_opt_in']) ? 1 : 0,
+             'id' => $reader['id'],
+         ]);
+     UserAuth::refreshPasswordFingerprint((int) $reader['id']);
+ 
+     return ['success', Language::get('account_profile_updated', 'Profile updated.'), 'profile'];
+ }
+ 
+ if ($action === 'change_password') {
      $newPassword = (string) ($_POST['new_password'] ?? '');
-     $currentPassword = (string) ($_POST['current_password'] ?? '');
+     $confirmPassword = (string) ($_POST['new_password_confirm'] ?? '');
+     if (!UserAuth::verifyPassword((int) $reader['id'], (string) ($_POST['current_password'] ?? ''))) {
+         return ['error', Language::get('account_current_password_wrong', 'Your current password is incorrect.'), 'profile'];
+     }
+     if (strlen($newPassword) < 8) {
+         return ['error', Language::get('auth_password_too_short', 'Password must be at least 8 characters.'), 'profile'];
+     }
+     if ($newPassword !== $confirmPassword) {
+         return ['error', Language::get('auth_password_mismatch', 'Passwords do not match.'), 'profile'];
+     }
+     $usersDb->prepare('UPDATE user_accounts SET password_hash = :hash WHERE id = :id')
+         ->execute(['hash' => password_hash($newPassword, PASSWORD_DEFAULT), 'id' => $reader['id']]);
+     session_regenerate_id(true);
+     UserAuth::refreshPasswordFingerprint((int) $reader['id']);
  
-     $params = ['display_name' => $displayName !== '' ? $displayName : $reader['display_name'], 'id' => $reader['id']];
+     return ['success', Language::get('account_password_updated', 'Password changed. Other devices were logged out.'), 'profile'];
+ }
  
-     if ($newPassword !== '') {
-         if (strlen($newPassword) < 8) {
-             return Language::get('auth_password_too_short', 'Password must be at least 8 characters.');
-         }
-         if (!UserAuth::verifyPassword((int) $reader['id'], $currentPassword)) {
-             return Language::get('account_current_password_wrong', 'Your current password is incorrect.');
-         }
-         $statement = Database::users()->prepare(
-             'UPDATE user_accounts SET display_name = :display_name, password_hash = :hash WHERE id = :id'
-         );
-         $statement->execute($params + ['hash' => password_hash($newPassword, PASSWORD_DEFAULT)]);
-         session_regenerate_id(true);
-         UserAuth::refreshPasswordFingerprint((int) $reader['id']);
+ if ($action === 'change_email') {
+     $newEmail = strtolower($accountText('new_email', 190));
+     if (!UserAuth::verifyPassword((int) $reader['id'], (string) ($_POST['current_password'] ?? ''))) {
+         return ['error', Language::get('account_current_password_wrong', 'Your current password is incorrect.'), 'profile'];
+     }
+     if ($newEmail === '' || !filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
+         return ['error', Language::get('auth_invalid_email', 'Please provide a valid email address.'), 'profile'];
+     }
+     if ($newEmail === strtolower((string) $reader['email'])) {
+         return ['error', Language::get('account_email_same', 'That is already your email address.'), 'profile'];
+     }
+     $taken = $usersDb->prepare('SELECT id FROM user_accounts WHERE email = :email AND id <> :id LIMIT 1');
+     $taken->execute(['email' => $newEmail, 'id' => $reader['id']]);
+     if ($taken->fetch()) {
+         return ['error', Language::get('auth_email_taken', 'An account with this email already exists.'), 'profile'];
+     }
+     $usersDb->prepare('UPDATE user_accounts SET email = :email, email_verified_at = NULL WHERE id = :id')
+         ->execute(['email' => $newEmail, 'id' => $reader['id']]);
+     UserAuth::refreshPasswordFingerprint((int) $reader['id']);
+     $updated = UserAuth::user();
+     if ($updated !== null) {
+         AccountEmails::sendVerification($updated);
+     }
+ 
+     return ['success', Language::get('account_email_changed', 'Email changed. We sent a confirmation link to the new address.'), 'profile'];
+ }
+ 
+ if ($action === 'resend_verification') {
+     $sent = AccountEmails::sendVerification($reader);
+ 
+     return $sent
+         ? ['success', Language::get('account_verification_sent', 'We sent you a new confirmation link.'), 'overview']
+         : ['error', Language::get('account_verification_wait', 'Please wait a minute before asking for another link.'), 'overview'];
+ }
+ 
+ if ($action === 'save_address') {
+     $addressId = (int) ($_POST['address_id'] ?? 0);
+     $fields = [
+         'label' => $accountText('label', 60),
+         'full_name' => $accountText('full_name', 190),
+         'company' => $accountText('company', 190),
+         'tax_id' => $accountText('tax_id', 60),
+         'address_line1' => $accountText('address_line1', 255),
+         'address_line2' => $accountText('address_line2', 255),
+         'city' => $accountText('city', 120),
+         'region' => $accountText('region', 120),
+         'postal_code' => $accountText('postal_code', 30),
+         'country' => strtoupper($accountText('country', 2)),
+         'phone' => $accountText('phone', 40),
+     ];
+     if ($fields['full_name'] === '' || $fields['address_line1'] === '' || $fields['city'] === '' || $fields['postal_code'] === '' || !Countries::isValid($fields['country'])) {
+         return ['error', Language::get('account_address_incomplete', 'Please fill in the name, address, postal code, city and country.'), 'addresses'];
+     }
+     $nullable = static fn(string $value): ?string => $value !== '' ? $value : null;
+     $params = [
+         'label' => $nullable($fields['label']),
+         'full_name' => $fields['full_name'],
+         'company' => $nullable($fields['company']),
+         'tax_id' => $nullable($fields['tax_id']),
+         'line1' => $fields['address_line1'],
+         'line2' => $nullable($fields['address_line2']),
+         'city' => $fields['city'],
+         'region' => $nullable($fields['region']),
+         'postal_code' => $fields['postal_code'],
+         'country' => $fields['country'],
+         'phone' => $nullable($fields['phone']),
+         'user_id' => $reader['id'],
+     ];
+ 
+     if ($addressId > 0) {
+         $usersDb->prepare(
+             'UPDATE user_addresses SET label = :label, full_name = :full_name, company = :company, tax_id = :tax_id, address_line1 = :line1, address_line2 = :line2,
+              city = :city, region = :region, postal_code = :postal_code, country = :country, phone = :phone WHERE id = :id AND user_account_id = :user_id'
+         )->execute($params + ['id' => $addressId]);
      } else {
-         $statement = Database::users()->prepare(
-             'UPDATE user_accounts SET display_name = :display_name WHERE id = :id'
-         );
-         $statement->execute($params);
-         UserAuth::refreshPasswordFingerprint((int) $reader['id']);
+         $countStatement = $usersDb->prepare('SELECT COUNT(*) FROM user_addresses WHERE user_account_id = :user_id');
+         $countStatement->execute(['user_id' => $reader['id']]);
+         $existingCount = (int) $countStatement->fetchColumn();
+         if ($existingCount >= 20) {
+             return ['error', Language::get('account_address_limit', 'You can save up to 20 addresses.'), 'addresses'];
+         }
+         $usersDb->prepare(
+             'INSERT INTO user_addresses (user_account_id, label, full_name, company, tax_id, address_line1, address_line2, city, region, postal_code, country, phone, is_default_shipping, is_default_billing)
+              VALUES (:user_id, :label, :full_name, :company, :tax_id, :line1, :line2, :city, :region, :postal_code, :country, :phone, :default_shipping, :default_billing)'
+         )->execute($params + ['default_shipping' => $existingCount === 0 ? 1 : 0, 'default_billing' => $existingCount === 0 ? 1 : 0]);
      }
  
-     return Language::get('account_profile_updated', 'Profile updated.');
+     return ['success', Language::get('account_address_saved', 'Address saved.'), 'addresses'];
  }
  
+ if ($action === 'delete_address') {
+     $usersDb->prepare('DELETE FROM user_addresses WHERE id = :id AND user_account_id = :user_id')
+         ->execute(['id' => (int) ($_POST['address_id'] ?? 0), 'user_id' => $reader['id']]);
+ 
+     return ['success', Language::get('account_address_deleted', 'Address deleted.'), 'addresses'];
+ }
+ 
+ if ($action === 'default_address') {
+     $addressId = (int) ($_POST['address_id'] ?? 0);
+     $column = ($_POST['kind'] ?? '') === 'billing' ? 'is_default_billing' : 'is_default_shipping';
+     $owns = $usersDb->prepare('SELECT id FROM user_addresses WHERE id = :id AND user_account_id = :user_id');
+     $owns->execute(['id' => $addressId, 'user_id' => $reader['id']]);
+     if ($owns->fetch()) {
+         $usersDb->prepare('UPDATE user_addresses SET ' . $column . ' = (id = :id) WHERE user_account_id = :user_id')
+             ->execute(['id' => $addressId, 'user_id' => $reader['id']]);
+     }
+ 
+     return ['success', Language::get('account_address_default_set', 'Default address changed.'), 'addresses'];
+ }
+ 
  if ($action === 'update_consents') {
      $consentTypes = ['analytics', 'ads_personalization'];
-     $db = Database::users();
  
      foreach ($consentTypes as $type) {
          $granted = isset($_POST['consent_' . $type]) ? 1 : 0;
  
-         $existingStatement = $db->prepare(
+         $existingStatement = $usersDb->prepare(
              'SELECT id FROM user_consents WHERE user_account_id = :user_id AND consent_type = :type ORDER BY id DESC LIMIT 1'
          );
          $existingStatement->execute(['user_id' => $reader['id'], 'type' => $type]);
          $existing = $existingStatement->fetch();
  
          if ($existing) {
-             $statement = $db->prepare(
+             $usersDb->prepare(
                  'UPDATE user_consents SET is_granted = :granted, granted_at = IF(:granted_check = 1, NOW(), granted_at), revoked_at = IF(:granted_check2 = 0, NOW(), NULL) WHERE id = :id'
-             );
-             $statement->execute(['granted' => $granted, 'granted_check' => $granted, 'granted_check2' => $granted, 'id' => $existing['id']]);
+             )->execute(['granted' => $granted, 'granted_check' => $granted, 'granted_check2' => $granted, 'id' => $existing['id']]);
          } else {
-             $statement = $db->prepare(
+             $usersDb->prepare(
                  'INSERT INTO user_consents (user_account_id, consent_type, is_granted, granted_at) VALUES (:user_id, :type, :granted, IF(:granted_check = 1, NOW(), NULL))'
-             );
-             $statement->execute(['user_id' => $reader['id'], 'type' => $type, 'granted' => $granted, 'granted_check' => $granted]);
+             )->execute(['user_id' => $reader['id'], 'type' => $type, 'granted' => $granted, 'granted_check' => $granted]);
          }
      }
  
-     return Language::get('account_preferences_updated', 'Preferences updated.');
+     return ['success', Language::get('account_preferences_updated', 'Preferences updated.'), 'privacy'];
+ }
+ 
+ if ($action === 'delete_account') {
+     if (!UserAuth::verifyPassword((int) $reader['id'], (string) ($_POST['current_password'] ?? ''))) {
+         return ['error', Language::get('account_current_password_wrong', 'Your current password is incorrect.'), 'privacy'];
+     }
+     if (($_POST['confirm_delete'] ?? '') !== '1') {
+         return ['error', Language::get('account_delete_confirm_missing', 'Please tick the box to confirm.'), 'privacy'];
+     }
+     $userId = (int) $reader['id'];
+     $usersDb->prepare("UPDATE orders SET guest_email = COALESCE(guest_email, :email) WHERE user_account_id = :id")
+         ->execute(['email' => $reader['email'], 'id' => $userId]);
+     $usersDb->prepare('DELETE FROM user_addresses WHERE user_account_id = :id')->execute(['id' => $userId]);
+     $usersDb->prepare('DELETE FROM account_tokens WHERE user_account_id = :id')->execute(['id' => $userId]);
+     $usersDb->prepare('DELETE FROM user_sessions WHERE user_account_id = :id')->execute(['id' => $userId]);
+     $usersDb->prepare(
+         "UPDATE user_accounts SET email = :email, display_name = NULL, phone = NULL, avatar_path = NULL, password_hash = :hash,
+          status = 'deleted', marketing_opt_in = 0 WHERE id = :id"
+     )->execute([
+         'email' => 'deleted-' . $userId . '-' . bin2hex(random_bytes(4)) . '@deleted.invalid',
+         'hash' => password_hash(bin2hex(random_bytes(32)), PASSWORD_DEFAULT),
+         'id' => $userId,
+     ]);
+     UserAuth::logout();
+ 
+     return ['deleted', Language::get('account_deleted', 'Your account was deleted.'), 'overview'];
  }
  
  return null;
⋮ 1 unchanged line ⋮
dashboard-actions/save-order-status.php Modified +43 -48
⋮ 10 unchanged lines ⋮
      return ['You don\'t have access to orders.', 'error', null];
  }
  
+ require_once __DIR__ . '/../includes/orders.php';
+ 
  $orderId = (int) ($_POST['order_id'] ?? 0);
  $allowedStatuses = ['pending', 'paid', 'processing', 'fulfilled', 'shipped', 'completed', 'canceled', 'refunded', 'failed'];
- $status = in_array($_POST['status'] ?? '', $allowedStatuses, true) ? $_POST['status'] : null;
- $trackingNumber = trim((string) ($_POST['tracking_number'] ?? ''));
+ $status = in_array($_POST['status'] ?? '', $allowedStatuses, true) ? (string) $_POST['status'] : null;
+ $trackingNumber = mb_substr(trim((string) ($_POST['tracking_number'] ?? '')), 0, 120);
  $trackingUrl = trim((string) ($_POST['tracking_url'] ?? ''));
+ $note = mb_substr(trim((string) ($_POST['note'] ?? '')), 0, 500);
+ $staffId = (int) $currentUser['id'];
+ 
  if ($trackingUrl !== '' && (!preg_match('#^https?://#i', $trackingUrl) || filter_var($trackingUrl, FILTER_VALIDATE_URL) === false)) {
      return ['The tracking link should start with http:// or https://.', 'error', $orderId > 0 ? $orderId : null];
  }
- $trackingNumber = mb_substr($trackingNumber, 0, 120);
- $note = mb_substr($note, 0, 2000);
- $note = trim((string) ($_POST['note'] ?? ''));
  
  if ($orderId <= 0 || $status === null) {
      return ['Something doesn\'t look right with that order. Please try again.', 'error', null];
  }
  
  $usersDb = Database::users();
- $statement = $usersDb->prepare('SELECT * FROM orders WHERE id = :id LIMIT 1');
- $statement->execute(['id' => $orderId]);
- $order = $statement->fetch();
- 
- if (!$order) {
+ $order = Orders::find($orderId);
+ if ($order === null) {
      return ['We couldn\'t find that order.', 'error', null];
  }
  
- $fulfilledAt = $order['fulfilled_at'];
- $shippedAt = $order['shipped_at'];
- if ($status === 'fulfilled' && $fulfilledAt === null) {
-     $fulfilledAt = date('Y-m-d H:i:s');
- }
- if ($status === 'shipped' && $shippedAt === null) {
-     $shippedAt = date('Y-m-d H:i:s');
- }
+ $previousStatus = (string) $order['status'];
+ $wasOpen = in_array($previousStatus, ['pending', 'failed'], true);
+ $isPaidStatus = in_array($status, Orders::PAID_STATUSES, true);
  
- $update = $usersDb->prepare(
-     'UPDATE orders SET status = :status, tracking_number = :tracking_number, tracking_url = :tracking_url,
-      fulfilled_at = :fulfilled_at, shipped_at = :shipped_at, updated_at = NOW() WHERE id = :id'
- );
- $update->execute([
-     'status' => $status,
-     'tracking_number' => $trackingNumber !== '' ? $trackingNumber : null,
-     'tracking_url' => $trackingUrl !== '' ? $trackingUrl : null,
-     'fulfilled_at' => $fulfilledAt,
-     'shipped_at' => $shippedAt,
-     'id' => $orderId,
- ]);
+ $usersDb->prepare('UPDATE orders SET tracking_number = :tracking_number, tracking_url = :tracking_url WHERE id = :id')
+     ->execute([
+         'tracking_number' => $trackingNumber !== '' ? $trackingNumber : null,
+         'tracking_url' => $trackingUrl !== '' ? $trackingUrl : null,
+         'id' => $orderId,
+     ]);
  
- $usersDb->prepare(
-     'INSERT INTO order_status_history (order_id, status, note, changed_by_team_account_id) VALUES (:order_id, :status, :note, :account_id)'
- )->execute([
-     'order_id' => $orderId,
-     'status' => $status,
-     'note' => $note !== '' ? $note : null,
-     'account_id' => $currentUser['id'],
- ]);
+ if ($isPaidStatus && $wasOpen) {
+     Orders::markPaid($orderId, ['provider' => (string) ($order['provider'] ?: 'manual')], $note !== '' ? $note : 'Marked as paid by staff', $staffId, $status);
+     return ['Order marked as paid. The customer got their confirmation, downloads and keys.', 'success', $orderId];
+ }
  
- $notifyCustomer = isset($_POST['notify_customer']);
- $recipientEmail = null;
- if ($order['user_account_id']) {
-     $accountStatement = $usersDb->prepare('SELECT email FROM user_accounts WHERE id = :id LIMIT 1');
-     $accountStatement->execute(['id' => $order['user_account_id']]);
-     $recipientEmail = $accountStatement->fetchColumn() ?: null;
- } else {
-     $recipientEmail = $order['guest_email'] ?: null;
+ if (in_array($status, Orders::CLOSED_STATUSES, true)) {
+     if ($status !== $previousStatus) {
+         Orders::close($orderId, $status, $note !== '' ? $note : null, $staffId, isset($_POST['restock']) || !isset($_POST['restock_present']));
+     }
+ } elseif ($status !== $previousStatus || $note !== '') {
+     $fulfilledAt = $order['fulfilled_at'];
+     $shippedAt = $order['shipped_at'];
+     if ($status === 'fulfilled' && $fulfilledAt === null) {
+         $fulfilledAt = date('Y-m-d H:i:s');
+     }
+     if ($status === 'shipped' && $shippedAt === null) {
+         $shippedAt = date('Y-m-d H:i:s');
+     }
+     $usersDb->prepare('UPDATE orders SET status = :status, fulfilled_at = :fulfilled_at, shipped_at = :shipped_at, updated_at = NOW() WHERE id = :id')
+         ->execute(['status' => $status, 'fulfilled_at' => $fulfilledAt, 'shipped_at' => $shippedAt, 'id' => $orderId]);
+     Orders::addHistory($orderId, $status, $note !== '' ? $note : null, $staffId);
  }
  
- if ($notifyCustomer && $recipientEmail && is_file(__DIR__ . '/../includes/mailer.php') && is_file(__DIR__ . '/../includes/mail-templates.php')) {
+ $notifyCustomer = isset($_POST['notify_customer']) && $status !== $previousStatus;
+ $recipientEmail = Orders::customerEmail($order);
+ 
+ if ($notifyCustomer && $recipientEmail !== null && is_file(__DIR__ . '/../includes/mailer.php') && is_file(__DIR__ . '/../includes/mail-templates.php')) {
      require_once __DIR__ . '/../includes/mailer.php';
      require_once __DIR__ . '/../includes/mail-templates.php';
      if (class_exists('Mailer') && class_exists('MailTemplates')) {
⋮ 3 unchanged lines ⋮
              'tracking_url' => $trackingUrl !== '' ? $trackingUrl : null,
          ]);
          try {
-             $email = MailTemplates::orderStatusEmail($updatedOrder, $status);
+             $email = MailTemplates::orderStatusEmail(Orders::ensureAccessToken($updatedOrder), $status);
              Mailer::send($recipientEmail, $email['subject'], $email['html']);
          } catch (Throwable $mailException) {
              error_log('StocketBase: order status email failed — ' . $mailException->getMessage());
⋮ 7 unchanged lines ⋮
dashboard-actions/save-settings.php Modified +75 -0
⋮ 230 unchanged lines ⋮
      ]);
  }
  
+ if ($settingsTab === 'shop') {
+     require_once __DIR__ . '/../includes/shop.php';
+ 
+     $shopCurrency = Currency::normalize((string) (SiteFront::settings()['store_currency'] ?? Currency::DEFAULT_CODE));
+     $shopDecimals = Currency::decimals($shopCurrency);
+     $toCents = static function ($raw) use ($shopDecimals): ?int {
+         $raw = str_replace([',', ' '], ['.', ''], trim((string) $raw));
+         if ($raw === '' || !is_numeric($raw)) {
+             return null;
+         }
+ 
+         return max(0, (int) round(((float) $raw) * (10 ** $shopDecimals)));
+     };
+     $shopText = static fn(string $key, int $max): string => mb_substr(trim((string) ($_POST[$key] ?? '')), 0, $max);
+     $shopEmail = static fn(string $key): string => filter_var(trim((string) ($_POST[$key] ?? '')), FILTER_VALIDATE_EMAIL) ?: '';
+ 
+     $methodRows = [];
+     $methodNames = is_array($_POST['shipping_name'] ?? null) ? array_values($_POST['shipping_name']) : [];
+     $methodIds = is_array($_POST['shipping_id'] ?? null) ? array_values($_POST['shipping_id']) : [];
+     $methodPrices = is_array($_POST['shipping_price'] ?? null) ? array_values($_POST['shipping_price']) : [];
+     $methodFree = is_array($_POST['shipping_free_over'] ?? null) ? array_values($_POST['shipping_free_over']) : [];
+     $methodCountries = is_array($_POST['shipping_countries'] ?? null) ? array_values($_POST['shipping_countries']) : [];
+     $methodNotes = is_array($_POST['shipping_note'] ?? null) ? array_values($_POST['shipping_note']) : [];
+     $methodCod = is_array($_POST['shipping_cod'] ?? null) ? $_POST['shipping_cod'] : [];
+     foreach ($methodNames as $index => $methodName) {
+         $methodRows[] = [
+             'id' => (string) ($methodIds[$index] ?? ''),
+             'name' => (string) $methodName,
+             'price_cents' => $toCents($methodPrices[$index] ?? '') ?? 0,
+             'free_over_cents' => $toCents($methodFree[$index] ?? ''),
+             'countries' => (string) ($methodCountries[$index] ?? ''),
+             'note' => (string) ($methodNotes[$index] ?? ''),
+             'cod' => isset($methodCod[$index]),
+         ];
+     }
+ 
+     $taxRateInput = str_replace(',', '.', trim((string) ($_POST['shop_tax_rate'] ?? '0')));
+     $taxRate = is_numeric($taxRateInput) ? max(0.0, min(100.0, (float) $taxRateInput)) : 0.0;
+     $defaultCountry = strtoupper(trim((string) ($_POST['shop_default_country'] ?? '')));
+     $invoiceFormat = $shopText('shop_invoice_format', 40);
+     if ($invoiceFormat === '' || !str_contains($invoiceFormat, '{number}')) {
+         $invoiceFormat = 'INV-{year}-{number}';
+     }
+ 
+     saveSettingsFields($db, [
+         'shop_shipping_methods' => json_encode(Shop::sanitizeShippingMethods($methodRows), JSON_UNESCAPED_UNICODE),
+         'shop_countries' => implode(',', Countries::parseList((string) ($_POST['shop_countries'] ?? ''))),
+         'shop_default_country' => Countries::isValid($defaultCountry) ? $defaultCountry : '',
+         'shop_tax_enabled' => isset($_POST['shop_tax_enabled']) ? '1' : '0',
+         'shop_tax_rate' => rtrim(rtrim(number_format($taxRate, 2, '.', ''), '0'), '.'),
+         'shop_tax_label' => $shopText('shop_tax_label', 30),
+         'shop_prices_include_tax' => isset($_POST['shop_prices_include_tax']) ? '1' : '0',
+         'shop_tax_shipping' => isset($_POST['shop_tax_shipping']) ? '1' : '0',
+         'shop_payment_card' => isset($_POST['shop_payment_card']) ? '1' : '0',
+         'shop_payment_bank' => isset($_POST['shop_payment_bank']) ? '1' : '0',
+         'shop_bank_details' => mb_substr(trim(strip_tags((string) ($_POST['shop_bank_details'] ?? ''))), 0, 2000),
+         'shop_bank_days' => (string) max(0, min(90, (int) ($_POST['shop_bank_days'] ?? 7))),
+         'shop_payment_cod' => isset($_POST['shop_payment_cod']) ? '1' : '0',
+         'shop_cod_fee_cents' => (string) ($toCents($_POST['shop_cod_fee'] ?? '') ?? 0),
+         'shop_phone_field' => in_array($_POST['shop_phone_field'] ?? 'optional', ['hidden', 'optional', 'required'], true) ? (string) $_POST['shop_phone_field'] : 'optional',
+         'shop_terms_url' => Shop::safeUrl((string) ($_POST['shop_terms_url'] ?? '')),
+         'shop_privacy_url' => Shop::safeUrl((string) ($_POST['shop_privacy_url'] ?? '')),
+         'shop_company_name' => $shopText('shop_company_name', 190),
+         'shop_company_address' => mb_substr(trim(strip_tags((string) ($_POST['shop_company_address'] ?? ''))), 0, 500),
+         'shop_tax_id' => $shopText('shop_tax_id', 60),
+         'shop_contact_email' => $shopEmail('shop_contact_email'),
+         'shop_invoice_format' => $invoiceFormat,
+         'shop_receipt_note' => mb_substr(trim(strip_tags((string) ($_POST['shop_receipt_note'] ?? ''))), 0, 1000),
+         'shop_notify_new_orders' => isset($_POST['shop_notify_new_orders']) ? '1' : '0',
+         'shop_notify_email' => $shopEmail('shop_notify_email'),
+         'shop_low_stock_threshold' => (string) max(0, min(10000, (int) ($_POST['shop_low_stock_threshold'] ?? 3))),
+     ]);
+     SiteFront::resetSettings();
+ }
+ 
  if ($settingsTab === 'email') {
      saveSettingsFields($db, [
          'mail_transport' => in_array($_POST['mail_transport'] ?? 'smtp', ['smtp', 'resend', 'postmark'], true) ? $_POST['mail_transport'] : 'smtp',
⋮ 46 unchanged lines ⋮
dashboard-views/order-detail.php Modified +125 -19
⋮ 35 unchanged lines ⋮
  
  $allowedStatuses = ['pending', 'paid', 'processing', 'fulfilled', 'shipped', 'completed', 'canceled', 'refunded', 'failed'];
  
+ require_once __DIR__ . '/../includes/orders.php';
+ require_once __DIR__ . '/../includes/countries.php';
+ $order = Orders::ensureAccessToken($order);
+ $paymentMethod = (string) ($order['payment_method'] ?: (in_array((string) $order['provider'], ['stripe', 'polar'], true) ? 'card' : (string) $order['provider']));
+ $orderIsPaid = in_array($order['status'], Orders::PAID_STATUSES, true);
+ $orderLicenses = Licenses::forOrder($orderId);
+ $orderGrants = DigitalFiles::grantRowsForOrder($orderId);
+ 
  ?>
+ <?php if (isset($_GET['saved'])): ?>
+ <div class="dash-flash dash-flash-success"><?= Icons::icon('check', 'icon icon-sm') ?>Saved.</div>
+ <?php endif; ?>
  <div class="dash-header-row">
  <h1 class="dash-title"><?= Icons::icon('checklist', 'icon icon-lg') ?>Order <?= htmlspecialchars($order['order_number']) ?></h1>
  <a href="dashboard.php?view=orders" class="dash-btn"><?= Icons::icon('checklist', 'icon icon-sm') ?>Back to orders</a>
  </div>
  
+ <?php if ($order['status'] === 'pending' && in_array($paymentMethod, ['bank_transfer', 'cod'], true)): ?>
+ <div class="sidebar-box order-pending-box">
+ <p><strong><?= $paymentMethod === 'bank_transfer' ? 'Waiting for the bank transfer.' : 'Cash on delivery — the customer pays the courier.' ?></strong>
+ <?= $paymentMethod === 'bank_transfer' ? ' Check your bank for a transfer titled <code>' . htmlspecialchars($order['order_number']) . '</code> of ' . htmlspecialchars(Currency::format((int) $order['total_cents'], $order['currency'])) . '.' : ' Ship it now, then mark it as paid when the money comes in.' ?>
+  Stock for this order is already set aside.</p>
+ <form method="post" style="display:flex;gap:8px;flex-wrap:wrap;">
+ <?= Csrf::field() ?>
+ <input type="hidden" name="action" value="update_order_status">
+ <input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
+ <input type="hidden" name="status" value="paid">
+ <input type="hidden" name="notify_customer" value="1">
+ <button type="submit" class="dash-btn dash-btn-primary"><?= Icons::icon('check', 'icon icon-sm') ?>Mark as paid</button>
+ </form>
+ </div>
+ <?php endif; ?>
+ 
  <div class="article-form-grid">
  <div class="article-form-main">
  
⋮ 13 unchanged lines ⋮
  </tbody>
  </table>
  
- <div class="sidebar-box" style="max-width:360px;margin-top:16px;">
- <p>Subtotal: <?= htmlspecialchars(Currency::format((int) $order['subtotal_cents'], $order['currency'])) ?></p>
+ <div class="sidebar-box order-totals-box" style="max-width:380px;margin-top:16px;">
+ <p><span>Subtotal</span><span><?= htmlspecialchars(Currency::format((int) $order['subtotal_cents'], $order['currency'])) ?></span></p>
  <?php if ((int) $order['discount_cents'] > 0): ?>
- <p>Discount<?= $order['discount_code'] ? ' (' . htmlspecialchars($order['discount_code']) . ')' : '' ?>: -<?= htmlspecialchars(Currency::format((int) $order['discount_cents'], $order['currency'])) ?></p>
+ <p><span>Discount<?= $order['discount_code'] ? ' (' . htmlspecialchars($order['discount_code']) . ')' : '' ?></span><span>-<?= htmlspecialchars(Currency::format((int) $order['discount_cents'], $order['currency'])) ?></span></p>
  <?php endif; ?>
- <?php if ((int) $order['shipping_cents'] > 0): ?>
- <p>Shipping: <?= htmlspecialchars(Currency::format((int) $order['shipping_cents'], $order['currency'])) ?></p>
+ <?php if ((int) $order['shipping_cents'] > 0 || !empty($order['shipping_method'])): ?>
+ <p><span>Shipping<?= !empty($order['shipping_method']) ? ' (' . htmlspecialchars($order['shipping_method']) . ')' : '' ?></span><span><?= htmlspecialchars(Currency::format((int) $order['shipping_cents'], $order['currency'])) ?></span></p>
  <?php endif; ?>
+ <?php if ((int) ($order['cod_fee_cents'] ?? 0) > 0): ?>
+ <p><span>Cash on delivery fee</span><span><?= htmlspecialchars(Currency::format((int) $order['cod_fee_cents'], $order['currency'])) ?></span></p>
+ <?php endif; ?>
  <?php if ((int) $order['tax_cents'] > 0): ?>
- <p>Tax: <?= htmlspecialchars(Currency::format((int) $order['tax_cents'], $order['currency'])) ?></p>
+ <p><span>Tax<?= (int) ($order['tax_rate_bp'] ?? 0) > 0 ? ' ' . htmlspecialchars(Shop::formatRate((int) $order['tax_rate_bp'])) : '' ?><?= (int) ($order['prices_include_tax'] ?? 0) === 1 ? ' (included)' : '' ?></span><span><?= htmlspecialchars(Currency::format((int) $order['tax_cents'], $order['currency'])) ?></span></p>
  <?php endif; ?>
- <p><strong>Total: <?= htmlspecialchars(Currency::format((int) $order['total_cents'], $order['currency'])) ?></strong></p>
+ <p class="order-totals-grand"><span>Total</span><span><?= htmlspecialchars(Currency::format((int) $order['total_cents'], $order['currency'])) ?></span></p>
  </div>
  
+ <?php
+ $dashShipping = Shop::addressLines($order, 'shipping');
+ $dashBilling = Shop::addressLines($order, 'billing');
+ if (!empty($dashShipping) && (int) ($order['billing_same_as_shipping'] ?? 1) === 1 && empty($order['billing_company']) && empty($order['billing_tax_id'])) {
+     $dashBilling = [];
+ }
+ ?>
+ <div class="order-address-columns">
+ <?php if (!empty($dashShipping)): ?>
+ <div>
  <h2 class="dash-subtitle"><?= Icons::icon('map-pin', 'icon icon-sm') ?>Shipping address</h2>
- <p>
- <?= htmlspecialchars((string) $order['shipping_name']) ?><br>
- <?= htmlspecialchars((string) $order['shipping_address_line1']) ?><br>
- <?php if (!empty($order['shipping_address_line2'])): ?><?= htmlspecialchars($order['shipping_address_line2']) ?><br><?php endif; ?>
- <?= htmlspecialchars((string) $order['shipping_city']) ?>, <?= htmlspecialchars((string) $order['shipping_region']) ?> <?= htmlspecialchars((string) $order['shipping_postal_code']) ?><br>
- <?= htmlspecialchars((string) $order['shipping_country']) ?>
- </p>
+ <p><?= implode('<br>', array_map(static fn(string $line): string => htmlspecialchars($line), $dashShipping)) ?></p>
+ </div>
+ <?php endif; ?>
+ <?php if (!empty($dashBilling)): ?>
+ <div>
+ <h2 class="dash-subtitle"><?= Icons::icon('credit-card', 'icon icon-sm') ?>Billing<?= !empty($order['billing_tax_id']) ? ' · invoice requested' : '' ?></h2>
+ <p><?= implode('<br>', array_map(static fn(string $line): string => htmlspecialchars($line), $dashBilling)) ?></p>
+ </div>
+ <?php endif; ?>
+ </div>
  
+ <?php if (!empty($orderLicenses)): ?>
+ <h2 class="dash-subtitle"><?= Icons::icon('lock', 'icon icon-sm') ?>License keys sent</h2>
+ <ul class="order-license-list">
+ <?php foreach ($orderLicenses as $orderLicense): ?>
+ <li><span><?= htmlspecialchars((string) $orderLicense['product_title_snapshot']) ?></span><code><?= htmlspecialchars((string) $orderLicense['license_key']) ?></code></li>
+ <?php endforeach; ?>
+ </ul>
+ <?php endif; ?>
+ 
+ <?php if (!empty($orderGrants)): ?>
+ <h2 class="dash-subtitle"><?= Icons::icon('download', 'icon icon-sm') ?>Download links</h2>
+ <table class="dash-table">
+ <thead><tr><th>Product</th><th>Downloads</th><th>Works until</th></tr></thead>
+ <tbody>
+ <?php foreach ($orderGrants as $grantProductId => $orderGrant): ?>
+ <?php $grantTitle = ''; foreach ($items as $grantItem) { if ((int) $grantItem['product_id'] === (int) $grantProductId) { $grantTitle = (string) $grantItem['product_title_snapshot']; } } ?>
+ <tr>
+ <td><?= htmlspecialchars($grantTitle) ?></td>
+ <td><?= (int) $orderGrant['download_count'] ?><?= $orderGrant['max_downloads'] !== null ? ' / ' . (int) $orderGrant['max_downloads'] : '' ?></td>
+ <td><?= htmlspecialchars((string) ($orderGrant['expires_at'] ?? 'No end date')) ?></td>
+ </tr>
+ <?php endforeach; ?>
+ </tbody>
+ </table>
+ <?php endif; ?>
+ 
  <?php if (!empty($order['customer_note'])): ?>
  <h2 class="dash-subtitle"><?= Icons::icon('message', 'icon icon-sm') ?>Customer note</h2>
  <p><?= nl2br(htmlspecialchars($order['customer_note'])) ?></p>
⋮ 23 unchanged lines ⋮
  
  <div class="sidebar-box">
  <label>Payment</label>
- <p>Paid with: <?= htmlspecialchars((string) ($order['provider'] ? ucfirst((string) $order['provider']) : 'Not paid yet')) ?><br>
- Payment reference: <?= htmlspecialchars((string) ($order['provider_payment_id'] ?: 'None yet')) ?></p>
+ <p>Method: <?= htmlspecialchars(Shop::paymentLabel($paymentMethod) ?: 'Unknown') ?><br>
+ <?php if (!empty($order['paid_at'])): ?>Paid on: <?= htmlspecialchars((string) $order['paid_at']) ?><br><?php endif; ?>
+ Payment reference: <?= htmlspecialchars((string) ($order['provider_payment_id'] ?: 'None yet')) ?>
+ <?php if (!empty($order['invoice_number'])): ?><br>Receipt number: <?= htmlspecialchars((string) $order['invoice_number']) ?><?php endif; ?>
+ <?php if (!empty($order['shipping_phone'])): ?><br>Phone: <a href="tel:<?= htmlspecialchars((string) $order['shipping_phone']) ?>"><?= htmlspecialchars((string) $order['shipping_phone']) ?></a><?php endif; ?></p>
  </div>
  
  <div class="sidebar-box">
+ <label>Customer links</label>
+ <div style="display:grid;gap:8px;">
+ <a href="<?= htmlspecialchars(Shop::orderUrl($order, false)) ?>" target="_blank" rel="noopener" class="dash-btn-small"><?= Icons::icon('eye', 'icon icon-sm') ?>Open the customer's order page</a>
+ <?php if ($orderIsPaid || $order['status'] === 'refunded'): ?>
+ <a href="<?= htmlspecialchars(Shop::receiptUrl($order)) ?>" target="_blank" rel="noopener" class="dash-btn-small"><?= Icons::icon('download', 'icon icon-sm') ?>Receipt</a>
+ <?php endif; ?>
+ <?php if ($orderIsPaid): ?>
+ <form method="post">
+ <?= Csrf::field() ?>
+ <input type="hidden" name="action" value="order_tools">
+ <input type="hidden" name="tool" value="resend">
+ <input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
+ <button type="submit" class="dash-btn-small" style="width:100%;"><?= Icons::icon('mail', 'icon icon-sm') ?>Send the confirmation again<?= !empty($orderLicenses) || !empty($orderGrants) ? ' (with downloads and keys)' : '' ?></button>
+ </form>
+ <?php if (!empty($orderGrants)): ?>
+ <form method="post">
+ <?= Csrf::field() ?>
+ <input type="hidden" name="action" value="order_tools">
+ <input type="hidden" name="tool" value="reset_downloads">
+ <input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
+ <button type="submit" class="dash-btn-small" style="width:100%;"><?= Icons::icon('refresh', 'icon icon-sm') ?>Reset download limits</button>
+ </form>
+ <?php endif; ?>
+ <?php endif; ?>
+ </div>
+ </div>
+ 
+ <div class="sidebar-box">
  <label>Change status</label>
  <form method="post">
  <?= Csrf::field() ?>
⋮ 11 unchanged lines ⋮
  <label>Note for the history (optional)</label>
  <input type="text" name="note">
  <label><input type="checkbox" name="notify_customer" checked> Let the customer know by email</label>
+ <input type="hidden" name="restock_present" value="1">
+ <label><input type="checkbox" name="restock" checked> Put the items back in stock if I cancel or refund</label>
+ <p style="font-size:12px;color:var(--muted);margin:6px 0 0;">Choosing Paid (or later) on an unpaid order sends the confirmation, download links and license keys. Canceled or Refunded turns off downloads and keys.</p>
  <button type="submit" class="dash-btn dash-btn-primary" style="margin-top:10px;"><?= Icons::icon('check', 'icon icon-sm') ?>Save status</button>
  </form>
  </div>
  
- <?php if (in_array($order['status'], ['paid', 'processing', 'fulfilled', 'shipped', 'completed'], true) && !empty($order['provider_payment_id'])): ?>
+ <?php if ($orderIsPaid): ?>
+ <?php $manualRefundOrder = in_array($paymentMethod, ['bank_transfer', 'cod', 'free'], true) || in_array((string) $order['provider'], ['manual', 'free'], true); ?>
  <div class="sidebar-box">
  <label>Refund</label>
- <form method="post" onsubmit="return confirm('Refund this order through ' + <?= json_encode($order['provider']) ?> + '? The money goes back to the customer and this can\'t be undone.');">
+ <p style="font-size:12.5px;color:var(--muted);margin:0 0 8px;"><?= $manualRefundOrder ? 'This order was paid outside the card system. We mark it as refunded and turn off downloads and keys; you send the money back yourself.' : 'The full amount goes back through ' . htmlspecialchars(ucfirst((string) $order['provider'])) . '. Downloads and license keys stop working.' ?></p>
+ <form method="post" onsubmit="return confirm(<?= htmlspecialchars((string) json_encode($manualRefundOrder ? 'Mark this order as refunded? This can\'t be undone.' : 'Refund this order? The money goes back to the customer and this can\'t be undone.'), ENT_QUOTES) ?>);">
  <?= Csrf::field() ?>
  <input type="hidden" name="action" value="refund_order">
  <input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
- <button type="submit" class="dash-btn dash-btn-danger"><?= Icons::icon('x', 'icon icon-sm') ?>Refund</button>
+ <label><input type="checkbox" name="restock" checked> Put the items back in stock</label>
+ <button type="submit" class="dash-btn dash-btn-danger"><?= Icons::icon('x', 'icon icon-sm') ?><?= $manualRefundOrder ? 'Mark as refunded' : 'Refund' ?></button>
  </form>
  </div>
  <?php endif; ?>
⋮ 4 unchanged lines ⋮
dashboard-views/orders.php Modified +4 -1
⋮ 7 unchanged lines ⋮
  }
  
  require_once __DIR__ . '/../includes/currency.php';
+ require_once __DIR__ . '/../includes/shop.php';
  
  if (!Auth::hasRoleAtLeast(Auth::ROLE_STORE_MANAGER)) {
      echo '<p>You don\'t have access to orders.</p>';
⋮ 33 unchanged lines ⋮
  <th><?= Icons::icon('hash', 'icon icon-sm') ?>Order</th>
  <th><?= Icons::icon('user', 'icon icon-sm') ?>Customer</th>
  <th><?= Icons::icon('dollar', 'icon icon-sm') ?>Total</th>
+ <th><?= Icons::icon('credit-card', 'icon icon-sm') ?>Payment</th>
  <th><?= Icons::icon('flag', 'icon icon-sm') ?>Status</th>
  <th><?= Icons::icon('clock', 'icon icon-sm') ?>Placed</th>
  <th></th>
⋮ 5 unchanged lines ⋮
  <td><?= htmlspecialchars($order['order_number']) ?></td>
  <td><?= htmlspecialchars((string) ($order['account_email'] ?: $order['guest_email'] ?: 'No email')) ?></td>
  <td><?= htmlspecialchars(Currency::format((int) $order['total_cents'], $order['currency'])) ?></td>
+ <td><?= htmlspecialchars(Shop::paymentLabel((string) (($order['payment_method'] ?? '') ?: (($order['provider'] ?? '') === 'stripe' ? 'card' : (string) ($order['provider'] ?? ''))))) ?></td>
  <td><span class="status-pill status-<?= htmlspecialchars($order['status']) ?>"><?= htmlspecialchars(StatusLabel::get((string) $order['status'])) ?></span></td>
  <td><?= htmlspecialchars($order['created_at']) ?></td>
  <td class="dash-table-actions"><a href="dashboard.php?view=order-detail&id=<?= (int) $order['id'] ?>" class="dash-btn-small"><?= Icons::icon('eye', 'icon icon-sm') ?>View</a></td>
  </tr>
  <?php endforeach; ?>
  <?php if (empty($orders)): ?>
- <tr><td colspan="6">No orders here yet.</td></tr>
+ <tr><td colspan="7">No orders here yet.</td></tr>
  <?php endif; ?>
  </tbody>
  </table>
⋮ 1 unchanged line ⋮
dashboard-views/product-edit.php Modified +77 -0
⋮ 237 unchanged lines ⋮
  </div>
  <?php endif; ?>
  
+ <?php if ($product && !$readOnlyMeta && Auth::hasRoleAtLeast(Auth::ROLE_STORE_MANAGER)): ?>
+ <?php
+ require_once __DIR__ . '/../includes/licenses.php';
+ $licenseMode = Licenses::mode($product);
+ $licenseCounts = Licenses::counts((int) $product['id']);
+ $licenseRows = $licenseMode === 'pool' || $licenseCounts['assigned'] > 0 ? Licenses::recentForProduct((int) $product['id'], 30) : [];
+ $licenseFlash = $_SESSION['license_flash'] ?? null;
+ unset($_SESSION['license_flash']);
+ ?>
+ <div class="sidebar-box" id="product-licenses">
+ <label><?= Icons::icon('lock', 'icon icon-sm') ?>License keys</label>
+ <?php if ($licenseFlash !== null): ?>
+ <div class="dash-flash dash-flash-success" style="margin:0 0 10px;"><?= Icons::icon('check', 'icon icon-sm') ?><?= htmlspecialchars((string) $licenseFlash) ?></div>
+ <?php endif; ?>
+ <p class="product-files-hint">Give every buyer a key, shown on the order page, in the email and in their account.</p>
+ <select name="license_mode" form="product-license-form" id="license-mode-select">
+ <option value="none" <?= $licenseMode === 'none' ? 'selected' : '' ?>>No keys</option>
+ <option value="generate" <?= $licenseMode === 'generate' ? 'selected' : '' ?>>New key for each purchase</option>
+ <option value="pool" <?= $licenseMode === 'pool' ? 'selected' : '' ?>>Keys from my own list</option>
+ </select>
+ <div data-license-section="generate" <?= $licenseMode === 'generate' ? '' : 'hidden' ?>>
+ <label>Key pattern (X = letter or digit, # = digit)</label>
+ <input type="text" name="license_pattern" form="product-license-form" maxlength="80" value="<?= htmlspecialchars((string) ($product['license_pattern'] ?? '')) ?>" placeholder="<?= htmlspecialchars(Licenses::DEFAULT_PATTERN) ?>">
+ <p class="product-files-hint">Example key: <code><?= htmlspecialchars(Licenses::generate((string) ($product['license_pattern'] ?? ''))) ?></code></p>
+ </div>
+ <div data-license-section="pool" <?= $licenseMode === 'pool' ? '' : 'hidden' ?>>
+ <p class="product-files-hint"><strong><?= (int) $licenseCounts['available'] ?></strong> keys left · <?= (int) $licenseCounts['assigned'] ?> sent<?= $licenseCounts['available'] === 0 ? ' · <span style="color:var(--danger);">add keys before you sell</span>' : '' ?></p>
+ <label>Add keys (one per line)</label>
+ <textarea name="license_keys" form="product-license-form" rows="4" placeholder="AAAA-BBBB-CCCC&#10;DDDD-EEEE-FFFF" spellcheck="false" style="font-family:monospace;font-size:12.5px;"></textarea>
+ </div>
+ <button type="submit" form="product-license-form" class="dash-btn-small"><?= Icons::icon('check', 'icon icon-sm') ?>Save keys</button>
+ <?php if (!empty($licenseRows)): ?>
+ <details style="margin-top:10px;">
+ <summary style="cursor:pointer;font-size:12.5px;">Show keys</summary>
+ <ul class="product-license-rows">
+ <?php foreach ($licenseRows as $licenseRow): ?>
+ <li>
+ <code><?= htmlspecialchars((string) $licenseRow['license_key']) ?></code>
+ <?php if ($licenseRow['order_id'] !== null): ?>
+ <a href="dashboard.php?view=order-detail&amp;id=<?= (int) $licenseRow['order_id'] ?>"><?= htmlspecialchars((string) ($licenseRow['order_number'] ?? ('#' . (int) $licenseRow['order_id']))) ?></a><?= $licenseRow['revoked_at'] !== null ? ' <small>(turned off)</small>' : '' ?>
+ <?php else: ?>
+ <button type="submit" form="product-license-delete-form" name="key_id" value="<?= (int) $licenseRow['id'] ?>" class="dash-btn-small dash-btn-danger" title="Remove this key"><?= Icons::icon('trash', 'icon icon-sm') ?></button>
+ <?php endif; ?>
+ </li>
+ <?php endforeach; ?>
+ </ul>
+ </details>
+ <?php endif; ?>
+ <script>
+ (function () {
+     var select = document.getElementById('license-mode-select');
+     if (!select) { return; }
+     function apply() {
+         document.querySelectorAll('[data-license-section]').forEach(function (section) {
+             section.hidden = section.getAttribute('data-license-section') !== select.value;
+         });
+     }
+     select.addEventListener('change', apply);
+ })();
+ </script>
+ </div>
+ <?php endif; ?>
+ 
  <div class="sidebar-box">
  <label>Stripe price ID (optional, leave empty to charge the price above)</label>
  <input type="text" name="stripe_price_id" value="<?= htmlspecialchars((string) ($product['stripe_price_id'] ?? '')) ?>" placeholder="price_..." <?= $readOnlyMeta ? 'readonly' : '' ?>>
⋮ 93 unchanged lines ⋮
  <form method="post" action="dashboard.php?view=product-edit&amp;id=<?= (int) $product['id'] ?>" id="product-file-delete-form">
  <?= Csrf::field() ?>
  <input type="hidden" name="action" value="delete_product_file">
+ <input type="hidden" name="product_id" value="<?= (int) $product['id'] ?>">
+ </form>
+ <?php endif; ?>
+ 
+ <?php if ($product && !$readOnlyMeta && Auth::hasRoleAtLeast(Auth::ROLE_STORE_MANAGER)): ?>
+ <form method="post" action="dashboard.php?view=product-edit&amp;id=<?= (int) $product['id'] ?>" id="product-license-form">
+ <?= Csrf::field() ?>
+ <input type="hidden" name="action" value="product_licenses">
+ <input type="hidden" name="product_id" value="<?= (int) $product['id'] ?>">
+ </form>
+ <form method="post" action="dashboard.php?view=product-edit&amp;id=<?= (int) $product['id'] ?>" id="product-license-delete-form" onsubmit="return confirm('Remove this key from the list?');">
+ <?= Csrf::field() ?>
+ <input type="hidden" name="action" value="product_licenses">
+ <input type="hidden" name="license_tool" value="delete_key">
  <input type="hidden" name="product_id" value="<?= (int) $product['id'] ?>">
  </form>
  <?php endif; ?>
⋮ 9 unchanged lines ⋮
dashboard.php Modified +19 -0
⋮ 160 unchanged lines ⋮
              }
          }
  
+         if ($action === 'order_tools') {
+             [$flashMessage, $flashType, $orderId] = require __DIR__ . '/dashboard-actions/order-tools.php';
+             if ($orderId !== null && $flashType === 'success') {
+                 ActivityLog::record('order.tools', 'order', (int) $orderId, (string) ($_POST['tool'] ?? ''));
+                 header('Location: dashboard.php?view=order-detail&id=' . $orderId . '&saved=1');
+                 exit;
+             }
+         }
+ 
+         if ($action === 'product_licenses') {
+             [$flashMessage, $flashType, $licenseProductId] = require __DIR__ . '/dashboard-actions/product-licenses.php';
+             if ($licenseProductId !== null && $flashType === 'success') {
+                 ActivityLog::record('product.licenses', 'product', (int) $licenseProductId, (string) ($_POST['license_mode'] ?? ''));
+                 $_SESSION['license_flash'] = $flashMessage;
+                 header('Location: dashboard.php?view=product-edit&id=' . (int) $licenseProductId . '&saved=1#product-licenses');
+                 exit;
+             }
+         }
+ 
          if ($action === 'refund_order') {
              [$flashMessage, $flashType, $orderId] = require __DIR__ . '/dashboard-actions/refund-order.php';
              if ($orderId !== null && $flashType === 'success') {
⋮ 102 unchanged lines ⋮
includes/account-emails.php Added +64 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/database.php';
+ require_once __DIR__ . '/account-tokens.php';
+ require_once __DIR__ . '/shop.php';
+ 
+ final class AccountEmails
+ {
+     public static function sendVerification(array $account): bool
+     {
+         if (!empty($account['email_verified_at']) || !self::loadMailer()) {
+             return false;
+         }
+         if (AccountTokens::recentlySent((int) $account['id'], AccountTokens::PURPOSE_VERIFY, 60)) {
+             return false;
+         }
+         $token = AccountTokens::create((int) $account['id'], AccountTokens::PURPOSE_VERIFY, 7 * 86400);
+         $message = MailTemplates::verifyEmail(Shop::baseUrl() . '/user-login.php?mode=verify&token=' . $token);
+ 
+         try {
+             return Mailer::send((string) $account['email'], $message['subject'], $message['html']);
+         } catch (Throwable $exception) {
+             error_log('StocketBase: verification email failed: ' . $exception->getMessage());
+ 
+             return false;
+         }
+     }
+ 
+     public static function sendPasswordReset(string $email): void
+     {
+         $email = strtolower(trim($email));
+         if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || !self::loadMailer()) {
+             return;
+         }
+         $statement = Database::users()->prepare("SELECT * FROM user_accounts WHERE email = :email AND status = 'active' LIMIT 1");
+         $statement->execute(['email' => $email]);
+         $account = $statement->fetch();
+         if (!$account || AccountTokens::recentlySent((int) $account['id'], AccountTokens::PURPOSE_RESET, 60)) {
+             return;
+         }
+         $token = AccountTokens::create((int) $account['id'], AccountTokens::PURPOSE_RESET, 3600);
+         $message = MailTemplates::passwordResetEmail(Shop::baseUrl() . '/user-login.php?mode=reset&token=' . $token);
+ 
+         try {
+             Mailer::send((string) $account['email'], $message['subject'], $message['html']);
+         } catch (Throwable $exception) {
+             error_log('StocketBase: password reset email failed: ' . $exception->getMessage());
+         }
+     }
+ 
+     private static function loadMailer(): bool
+     {
+         if (!is_file(__DIR__ . '/mailer.php') || !is_file(__DIR__ . '/mail-templates.php')) {
+             return false;
+         }
+         require_once __DIR__ . '/mailer.php';
+         require_once __DIR__ . '/mail-templates.php';
+ 
+         return class_exists('Mailer') && class_exists('MailTemplates');
+     }
+ }
+ 
includes/account-order-list.php Added +23 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ if (count(get_included_files()) === 1) {
+     http_response_code(403);
+     exit;
+ }
+ 
+ ?>
+ <div class="account-orders">
+     <?php foreach ($recentOrders as $orderRow): ?>
+         <a class="account-order" href="account.php?tab=orders&amp;order=<?= (int) $orderRow['id'] ?>">
+             <span class="account-order-main">
+                 <strong><?= htmlspecialchars((string) $orderRow['order_number']) ?></strong>
+                 <small><?= htmlspecialchars(OrderView::date((string) $orderRow['created_at'])) ?></small>
+             </span>
+             <span class="status-pill status-<?= htmlspecialchars((string) $orderRow['status']) ?>"><?= htmlspecialchars(OrderView::statusLabel((string) $orderRow['status'])) ?></span>
+             <span class="account-order-total"><?= htmlspecialchars(Currency::format((int) $orderRow['total_cents'], (string) $orderRow['currency'])) ?></span>
+         </a>
+     <?php endforeach; ?>
+ </div>
+ 
includes/account-tokens.php Added +70 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/database.php';
+ 
+ final class AccountTokens
+ {
+     public const PURPOSE_RESET = 'reset';
+     public const PURPOSE_VERIFY = 'verify';
+ 
+     public static function create(int $userAccountId, string $purpose, int $ttlSeconds): string
+     {
+         $usersDb = Database::users();
+         $usersDb->prepare('DELETE FROM account_tokens WHERE user_account_id = :user_id AND purpose = :purpose')
+             ->execute(['user_id' => $userAccountId, 'purpose' => $purpose]);
+         $usersDb->prepare('DELETE FROM account_tokens WHERE expires_at < NOW() - INTERVAL 7 DAY')->execute();
+ 
+         $token = bin2hex(random_bytes(32));
+         $usersDb->prepare(
+             'INSERT INTO account_tokens (user_account_id, purpose, token_hash, expires_at) VALUES (:user_id, :purpose, :hash, NOW() + INTERVAL :ttl SECOND)'
+         )->execute([
+             'user_id' => $userAccountId,
+             'purpose' => $purpose,
+             'hash' => hash('sha256', $token),
+             'ttl' => max(60, $ttlSeconds),
+         ]);
+ 
+         return $token;
+     }
+ 
+     public static function peek(string $token, string $purpose): ?int
+     {
+         if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
+             return null;
+         }
+         $statement = Database::users()->prepare(
+             'SELECT user_account_id FROM account_tokens WHERE token_hash = :hash AND purpose = :purpose AND used_at IS NULL AND expires_at > NOW() LIMIT 1'
+         );
+         $statement->execute(['hash' => hash('sha256', $token), 'purpose' => $purpose]);
+         $userId = $statement->fetchColumn();
+ 
+         return $userId !== false ? (int) $userId : null;
+     }
+ 
+     public static function consume(string $token, string $purpose): ?int
+     {
+         $userId = self::peek($token, $purpose);
+         if ($userId === null) {
+             return null;
+         }
+         $update = Database::users()->prepare(
+             'UPDATE account_tokens SET used_at = NOW() WHERE token_hash = :hash AND purpose = :purpose AND used_at IS NULL'
+         );
+         $update->execute(['hash' => hash('sha256', $token), 'purpose' => $purpose]);
+ 
+         return $update->rowCount() > 0 ? $userId : null;
+     }
+ 
+     public static function recentlySent(int $userAccountId, string $purpose, int $seconds): bool
+     {
+         $statement = Database::users()->prepare(
+             'SELECT 1 FROM account_tokens WHERE user_account_id = :user_id AND purpose = :purpose AND created_at > NOW() - INTERVAL :seconds SECOND LIMIT 1'
+         );
+         $statement->execute(['user_id' => $userAccountId, 'purpose' => $purpose, 'seconds' => max(1, $seconds)]);
+ 
+         return (bool) $statement->fetchColumn();
+     }
+ }
+ 
includes/countries.php Added +99 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ final class Countries
+ {
+     private const LIST = [
+         'AF' => 'Afghanistan', 'AX' => '�
+ land Islands', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AS' => 'American Samoa',
+         'AD' => 'Andorra', 'AO' => 'Angola', 'AI' => 'Anguilla', 'AQ' => 'Antarctica', 'AG' => 'Antigua and Barbuda',
+         'AR' => 'Argentina', 'AM' => 'Armenia', 'AW' => 'Aruba', 'AU' => 'Australia', 'AT' => 'Austria',
+         'AZ' => 'Azerbaijan', 'BS' => 'Bahamas', 'BH' => 'Bahrain', 'BD' => 'Bangladesh', 'BB' => 'Barbados',
+         'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin', 'BM' => 'Bermuda',
+         'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BQ' => 'Caribbean Netherlands', 'BA' => 'Bosnia and Herzegovina', 'BW' => 'Botswana',
+         'BV' => 'Bouvet Island', 'BR' => 'Brazil', 'IO' => 'British Indian Ocean Territory', 'BN' => 'Brunei', 'BG' => 'Bulgaria',
+         'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'CV' => 'Cape Verde', 'KH' => 'Cambodia', 'CM' => 'Cameroon',
+         'CA' => 'Canada', 'KY' => 'Cayman Islands', 'CF' => 'Central African Republic', 'TD' => 'Chad', 'CL' => 'Chile',
+         'CN' => 'China', 'CX' => 'Christmas Island', 'CC' => 'Cocos (Keeling) Islands', 'CO' => 'Colombia', 'KM' => 'Comoros',
+         'CG' => 'Congo', 'CD' => 'Congo (DRC)', 'CK' => 'Cook Islands', 'CR' => 'Costa Rica', 'CI' => 'Côte d’Ivoire',
+         'HR' => 'Croatia', 'CU' => 'Cuba', 'CW' => 'Curaçao', 'CY' => 'Cyprus', 'CZ' => 'Czechia',
+         'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DM' => 'Dominica', 'DO' => 'Dominican Republic', 'EC' => 'Ecuador',
+         'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'EE' => 'Estonia',
+         'SZ' => 'Eswatini', 'ET' => 'Ethiopia', 'FK' => 'Falkland Islands', 'FO' => 'Faroe Islands', 'FJ' => 'Fiji',
+         'FI' => 'Finland', 'FR' => 'France', 'GF' => 'French Guiana', 'PF' => 'French Polynesia', 'TF' => 'French Southern Territories',
+         'GA' => 'Gabon', 'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana',
+         'GI' => 'Gibraltar', 'GR' => 'Greece', 'GL' => 'Greenland', 'GD' => 'Grenada', 'GP' => 'Guadeloupe',
+         'GU' => 'Guam', 'GT' => 'Guatemala', 'GG' => 'Guernsey', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau',
+         'GY' => 'Guyana', 'HT' => 'Haiti', 'HM' => 'Heard and McDonald Islands', 'VA' => 'Vatican City', 'HN' => 'Honduras',
+         'HK' => 'Hong Kong', 'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia',
+         'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IM' => 'Isle of Man', 'IL' => 'Israel',
+         'IT' => 'Italy', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JE' => 'Jersey', 'JO' => 'Jordan',
+         'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'KP' => 'North Korea', 'KR' => 'South Korea',
+         'XK' => 'Kosovo', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan', 'LA' => 'Laos', 'LV' => 'Latvia',
+         'LB' => 'Lebanon', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein',
+         'LT' => 'Lithuania', 'LU' => 'Luxembourg', 'MO' => 'Macao', 'MG' => 'Madagascar', 'MW' => 'Malawi',
+         'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta', 'MH' => 'Marshall Islands',
+         'MQ' => 'Martinique', 'MR' => 'Mauritania', 'MU' => 'Mauritius', 'YT' => 'Mayotte', 'MX' => 'Mexico',
+         'FM' => 'Micronesia', 'MD' => 'Moldova', 'MC' => 'Monaco', 'MN' => 'Mongolia', 'ME' => 'Montenegro',
+         'MS' => 'Montserrat', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'MM' => 'Myanmar', 'NA' => 'Namibia',
+         'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands', 'NC' => 'New Caledonia', 'NZ' => 'New Zealand',
+         'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria', 'NU' => 'Niue', 'NF' => 'Norfolk Island',
+         'MK' => 'North Macedonia', 'MP' => 'Northern Mariana Islands', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan',
+         'PW' => 'Palau', 'PS' => 'Palestine', 'PA' => 'Panama', 'PG' => 'Papua New Guinea', 'PY' => 'Paraguay',
+         'PE' => 'Peru', 'PH' => 'Philippines', 'PN' => 'Pitcairn Islands', 'PL' => 'Poland', 'PT' => 'Portugal',
+         'PR' => 'Puerto Rico', 'QA' => 'Qatar', 'RE' => 'Réunion', 'RO' => 'Romania', 'RU' => 'Russia',
+         'RW' => 'Rwanda', 'BL' => 'Saint Barthélemy', 'SH' => 'Saint Helena', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia',
+         'MF' => 'Saint Martin', 'PM' => 'Saint Pierre and Miquelon', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa', 'SM' => 'San Marino',
+         'ST' => 'São Tomé and Príncipe', 'SA' => 'Saudi Arabia', 'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles',
+         'SL' => 'Sierra Leone', 'SG' => 'Singapore', 'SX' => 'Sint Maarten', 'SK' => 'Slovakia', 'SI' => 'Slovenia',
+         'SB' => 'Solomon Islands', 'SO' => 'Somalia', 'ZA' => 'South Africa', 'GS' => 'South Georgia and South Sandwich Islands', 'SS' => 'South Sudan',
+         'ES' => 'Spain', 'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'SJ' => 'Svalbard and Jan Mayen',
+         'SE' => 'Sweden', 'CH' => 'Switzerland', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan',
+         'TZ' => 'Tanzania', 'TH' => 'Thailand', 'TL' => 'Timor-Leste', 'TG' => 'Togo', 'TK' => 'Tokelau',
+         'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Türkiye', 'TM' => 'Turkmenistan',
+         'TC' => 'Turks and Caicos Islands', 'TV' => 'Tuvalu', 'UG' => 'Uganda', 'UA' => 'Ukraine', 'AE' => 'United Arab Emirates',
+         'GB' => 'United Kingdom', 'US' => 'United States', 'UM' => 'U.S. Outlying Islands', 'UY' => 'Uruguay', 'UZ' => 'Uzbekistan',
+         'VU' => 'Vanuatu', 'VE' => 'Venezuela', 'VN' => 'Vietnam', 'VG' => 'British Virgin Islands', 'VI' => 'U.S. Virgin Islands',
+         'WF' => 'Wallis and Futuna', 'EH' => 'Western Sahara', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe',
+     ];
+ 
+     public static function all(): array
+     {
+         $list = self::LIST;
+         uasort($list, static fn(string $a, string $b): int => strcmp(self::sortKey($a), self::sortKey($b)));
+ 
+         return $list;
+     }
+ 
+     public static function isValid(string $code): bool
+     {
+         return isset(self::LIST[strtoupper($code)]);
+     }
+ 
+     public static function name(string $code): string
+     {
+         $code = strtoupper(trim($code));
+ 
+         return self::LIST[$code] ?? $code;
+     }
+ 
+     public static function parseList(string $raw): array
+     {
+         $codes = [];
+         foreach (preg_split('/[\s,;]+/', strtoupper($raw)) ?: [] as $code) {
+             if ($code !== '' && isset(self::LIST[$code])) {
+                 $codes[$code] = true;
+             }
+         }
+ 
+         return array_keys($codes);
+     }
+ 
+     private static function sortKey(string $name): string
+     {
+         return strtr($name, ['�
+ ' => 'A', 'Ô' => 'O', 'ô' => 'o', 'é' => 'e', 'ç' => 'c', 'ã' => 'a', 'í' => 'i', 'ü' => 'u', 'Ü' => 'U', 'ão' => 'ao']);
+     }
+ }
+ 
includes/database.php Modified +138 -0
⋮ 8 unchanged lines ⋮
      private static ?PDO $site = null;
      private static ?PDO $users = null;
      private static bool $schemaChecked = false;
+     private static bool $usersSchemaChecked = false;
  
      public static function site(): PDO
      {
⋮ 28 unchanged lines ⋮
              Config::get('DB_USERS_PASS', '')
          );
  
+         self::ensureUsersSchema(self::$users);
+ 
          return self::$users;
      }
  
+     private static function ensureUsersSchema(PDO $pdo): void
+     {
+         if (self::$usersSchemaChecked) {
+             return;
+         }
+         self::$usersSchemaChecked = true;
+ 
+         try {
+             $dbName = (string) $pdo->query('SELECT DATABASE()')->fetchColumn();
+             if ($dbName === '') {
+                 return;
+             }
+ 
+             $tablesStatement = $pdo->prepare('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = :db');
+             $tablesStatement->execute(['db' => $dbName]);
+             $existingTables = array_map('strtolower', $tablesStatement->fetchAll(PDO::FETCH_COLUMN));
+ 
+             $columnsStatement = $pdo->prepare('SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :db AND TABLE_NAME IN (\'orders\', \'user_accounts\')');
+             $columnsStatement->execute(['db' => $dbName]);
+             $existingColumns = [];
+             foreach ($columnsStatement->fetchAll() as $row) {
+                 $existingColumns[strtolower((string) $row['TABLE_NAME'])][strtolower((string) $row['COLUMN_NAME'])] = true;
+             }
+ 
+             $requiredColumns = [
+                 'orders' => [
+                     'payment_method' => 'ALTER TABLE orders ADD COLUMN payment_method VARCHAR(30) NULL AFTER provider',
+                     'shipping_method' => 'ALTER TABLE orders ADD COLUMN shipping_method VARCHAR(160) NULL AFTER shipping_cents',
+                     'shipping_phone' => 'ALTER TABLE orders ADD COLUMN shipping_phone VARCHAR(40) NULL AFTER shipping_country',
+                     'billing_company' => 'ALTER TABLE orders ADD COLUMN billing_company VARCHAR(190) NULL AFTER billing_name',
+                     'billing_tax_id' => 'ALTER TABLE orders ADD COLUMN billing_tax_id VARCHAR(60) NULL AFTER billing_company',
+                     'prices_include_tax' => 'ALTER TABLE orders ADD COLUMN prices_include_tax TINYINT(1) NOT NULL DEFAULT 0 AFTER tax_cents',
+                     'tax_rate_bp' => 'ALTER TABLE orders ADD COLUMN tax_rate_bp INT UNSIGNED NOT NULL DEFAULT 0 AFTER prices_include_tax',
+                     'access_token' => 'ALTER TABLE orders ADD COLUMN access_token CHAR(64) NULL, ADD UNIQUE KEY uq_order_access_token (access_token)',
+                     'invoice_number' => 'ALTER TABLE orders ADD COLUMN invoice_number VARCHAR(40) NULL',
+                     'paid_at' => 'ALTER TABLE orders ADD COLUMN paid_at DATETIME NULL',
+                     'canceled_at' => 'ALTER TABLE orders ADD COLUMN canceled_at DATETIME NULL',
+                     'stock_reserved' => 'ALTER TABLE orders ADD COLUMN stock_reserved TINYINT(1) NOT NULL DEFAULT 0',
+                     'cod_fee_cents' => 'ALTER TABLE orders ADD COLUMN cod_fee_cents INT UNSIGNED NOT NULL DEFAULT 0 AFTER shipping_cents',
+                 ],
+                 'user_accounts' => [
+                     'phone' => 'ALTER TABLE user_accounts ADD COLUMN phone VARCHAR(40) NULL AFTER display_name',
+                     'marketing_opt_in' => 'ALTER TABLE user_accounts ADD COLUMN marketing_opt_in TINYINT(1) NOT NULL DEFAULT 0',
+                 ],
+             ];
+ 
+             foreach ($requiredColumns as $table => $columns) {
+                 if (!in_array($table, $existingTables, true)) {
+                     continue;
+                 }
+                 foreach ($columns as $column => $sql) {
+                     if (isset($existingColumns[$table][$column])) {
+                         continue;
+                     }
+                     try {
+                         $pdo->exec($sql);
+                     } catch (PDOException $e) {
+                         error_log('StocketBase: could not auto-add column ' . $table . '.' . $column . ': ' . $e->getMessage());
+                     }
+                 }
+             }
+ 
+             foreach (self::usersTableDefinitions() as $table => $sql) {
+                 if (in_array($table, $existingTables, true)) {
+                     continue;
+                 }
+                 try {
+                     $pdo->exec($sql);
+                 } catch (PDOException $e) {
+                     error_log('StocketBase: could not auto-create table ' . $table . ': ' . $e->getMessage());
+                 }
+             }
+         } catch (PDOException $e) {
+             error_log('StocketBase: users schema auto-check failed: ' . $e->getMessage());
+         }
+     }
+ 
+     public static function usersTableDefinitions(): array
+     {
+         return [
+             'user_addresses' => "CREATE TABLE user_addresses (
+                 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+                 user_account_id INT UNSIGNED NOT NULL,
+                 label VARCHAR(60) NULL,
+                 full_name VARCHAR(190) NOT NULL,
+                 company VARCHAR(190) NULL,
+                 tax_id VARCHAR(60) NULL,
+                 address_line1 VARCHAR(255) NOT NULL,
+                 address_line2 VARCHAR(255) NULL,
+                 city VARCHAR(120) NOT NULL,
+                 region VARCHAR(120) NULL,
+                 postal_code VARCHAR(30) NOT NULL,
+                 country CHAR(2) NOT NULL,
+                 phone VARCHAR(40) NULL,
+                 is_default_shipping TINYINT(1) NOT NULL DEFAULT 0,
+                 is_default_billing TINYINT(1) NOT NULL DEFAULT 0,
+                 created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+                 updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+                 KEY idx_address_account (user_account_id),
+                 CONSTRAINT fk_address_account FOREIGN KEY (user_account_id) REFERENCES user_accounts(id) ON DELETE CASCADE
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
+             'account_tokens' => "CREATE TABLE account_tokens (
+                 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+                 user_account_id INT UNSIGNED NOT NULL,
+                 purpose VARCHAR(20) NOT NULL,
+                 token_hash CHAR(64) NOT NULL,
+                 expires_at DATETIME NOT NULL,
+                 used_at DATETIME NULL,
+                 created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+                 UNIQUE KEY uq_account_token_hash (token_hash),
+                 KEY idx_account_token_user (user_account_id, purpose),
+                 CONSTRAINT fk_account_token_account FOREIGN KEY (user_account_id) REFERENCES user_accounts(id) ON DELETE CASCADE
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
+             'license_keys' => "CREATE TABLE license_keys (
+                 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+                 product_id INT UNSIGNED NOT NULL,
+                 license_key VARCHAR(255) NOT NULL,
+                 source ENUM('pool','generated') NOT NULL DEFAULT 'pool',
+                 order_id INT UNSIGNED NULL,
+                 order_item_id INT UNSIGNED NULL,
+                 user_account_id INT UNSIGNED NULL,
+                 assigned_at DATETIME NULL,
+                 revoked_at DATETIME NULL,
+                 created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+                 UNIQUE KEY uq_license_product_key (product_id, license_key),
+                 KEY idx_license_free (product_id, order_id),
+                 KEY idx_license_order (order_id),
+                 KEY idx_license_account (user_account_id)
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
+         ];
+     }
+ 
      private static function connect(?string $host, ?string $port, ?string $name, ?string $user, ?string $pass): PDO
      {
          $dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $name);
⋮ 67 unchanged lines ⋮
                  'products' => [
                      'deleted_at' => "ALTER TABLE products ADD COLUMN deleted_at DATETIME NULL",
                      'trashed_status' => "ALTER TABLE products ADD COLUMN trashed_status VARCHAR(20) NULL",
+                     'license_mode' => "ALTER TABLE products ADD COLUMN license_mode VARCHAR(10) NOT NULL DEFAULT 'none'",
+                     'license_pattern' => "ALTER TABLE products ADD COLUMN license_pattern VARCHAR(80) NULL",
+                     'low_stock_alerted_at' => "ALTER TABLE products ADD COLUMN low_stock_alerted_at DATETIME NULL",
                  ],
                  'pages' => [
                      'is_home' => "ALTER TABLE pages ADD COLUMN is_home TINYINT(1) NOT NULL DEFAULT 0",
⋮ 228 unchanged lines ⋮
includes/digital-files.php Modified +100 -5
⋮ 310 unchanged lines ⋮
  
          $downloadName = (string) $file['original_name'];
          $asciiName = (string) preg_replace('/[^A-Za-z0-9._ -]/', '_', $downloadName);
+         $size = (int) filesize($path);
+         $etag = '"' . substr((string) ($file['sha256'] ?? md5($path . $size)), 0, 32) . '"';
+         [$start, $end] = self::requestedRange($size, $etag);
  
+         if ($start === null) {
+             http_response_code(416);
+             header('Content-Range: bytes */' . $size);
+             exit;
+         }
+ 
+         $length = $end - $start + 1;
+         if ($start > 0 || $end < $size - 1) {
+             http_response_code(206);
+             header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
+         }
+ 
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($downloadName));
-         header('Content-Length: ' . (int) filesize($path));
+         header('Content-Length: ' . $length);
+         header('Accept-Ranges: bytes');
+         header('ETag: ' . $etag);
          header('Content-Transfer-Encoding: binary');
          header('X-Content-Type-Options: nosniff');
          header('Content-Security-Policy: default-src \'none\'; sandbox');
          header('Cache-Control: private, no-store, max-age=0');
          header('X-Robots-Tag: noindex, nofollow');
  
+         if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'HEAD') {
+             exit;
+         }
+ 
          $handle = fopen($path, 'rb');
          if ($handle !== false) {
-             while (!feof($handle)) {
-                 echo fread($handle, 1048576);
+             if ($start > 0) {
+                 fseek($handle, $start);
+             }
+             $remaining = $length;
+             while ($remaining > 0 && !feof($handle)) {
+                 $chunk = fread($handle, (int) min(1048576, $remaining));
+                 if ($chunk === false || $chunk === '') {
+                     break;
+                 }
+                 echo $chunk;
+                 $remaining -= strlen($chunk);
                  flush();
                  if (connection_aborted()) {
                      break;
⋮ 4 unchanged lines ⋮
          exit;
      }
  
+     public static function requestedRange(int $size, string $etag = ''): array
+     {
+         $full = [0, max(0, $size - 1)];
+         $header = trim((string) ($_SERVER['HTTP_RANGE'] ?? ''));
+         if ($header === '' || $size <= 0) {
+             return $full;
+         }
+         $ifRange = trim((string) ($_SERVER['HTTP_IF_RANGE'] ?? ''));
+         if ($ifRange !== '' && $etag !== '' && $ifRange !== $etag) {
+             return $full;
+         }
+         if (preg_match('/^bytes=(\d*)-(\d*)$/', $header, $match) !== 1 || ($match[1] === '' && $match[2] === '')) {
+             return $full;
+         }
+         if ($match[1] === '') {
+             $suffix = (int) $match[2];
+             if ($suffix <= 0) {
+                 return [null, null];
+             }
+ 
+             return [max(0, $size - $suffix), $size - 1];
+         }
+         $start = (int) $match[1];
+         $end = $match[2] === '' ? $size - 1 : min((int) $match[2], $size - 1);
+         if ($start >= $size || $start > $end) {
+             return [null, null];
+         }
+ 
+         return [$start, $end];
+     }
+ 
+     public static function isContinuationRequest(): bool
+     {
+         $header = trim((string) ($_SERVER['HTTP_RANGE'] ?? ''));
+ 
+         return preg_match('/^bytes=(\d+)-/', $header, $match) === 1 && (int) $match[1] > 0;
+     }
+ 
      public static function sanitizeFileName(string $name): string
      {
          $name = str_replace(['\\', '/'], '_', $name);
⋮ 159 unchanged lines ⋮
                  $token = bin2hex(random_bytes(32));
                  $usersDb->prepare(
                      'INSERT INTO download_grants (token, product_id, order_id, user_account_id, email, max_downloads, expires_at)
-                      VALUES (:token, :product_id, :order_id, :user_account_id, :email, :max_downloads, :expires_at)'
+                      VALUES (:token, :product_id, :order_id, :user_account_id, :email, :max_downloads, ' . ($expiryDays > 0 ? 'NOW() + INTERVAL ' . $expiryDays . ' DAY' : 'NULL') . ')'
                  )->execute([
                      'token' => $token,
                      'product_id' => $productId,
⋮ 1 unchanged line ⋮
                      'user_account_id' => $order['user_account_id'] !== null ? (int) $order['user_account_id'] : null,
                      'email' => $email !== '' ? $email : null,
                      'max_downloads' => $maxDownloads > 0 ? $maxDownloads : null,
-                     'expires_at' => $expiryDays > 0 ? date('Y-m-d H:i:s', time() + $expiryDays * 86400) : null,
                  ]);
              }
  
⋮ 57 unchanged lines ⋮
          self::ensureUsersSchema($usersDb);
          $usersDb->prepare('UPDATE download_grants SET revoked_at = NOW() WHERE order_id = :order_id AND revoked_at IS NULL')
              ->execute(['order_id' => $orderId]);
+     }
+ 
+     public static function grantRowsForOrder(int $orderId): array
+     {
+         $usersDb = Database::users();
+         self::ensureUsersSchema($usersDb);
+         $statement = $usersDb->prepare('SELECT * FROM download_grants WHERE order_id = :order_id AND revoked_at IS NULL');
+         $statement->execute(['order_id' => $orderId]);
+ 
+         $grants = [];
+         foreach ($statement->fetchAll() as $row) {
+             $grants[(int) $row['product_id']] = $row;
+         }
+ 
+         return $grants;
+     }
+ 
+     public static function resetGrantsForOrder(int $orderId): int
+     {
+         $settings = SiteFront::settings();
+         $expiryDays = max(0, (int) ($settings['download_link_expiry_days'] ?? 30));
+         $statement = Database::users()->prepare(
+             'UPDATE download_grants SET download_count = 0, expires_at = ' . ($expiryDays > 0 ? 'NOW() + INTERVAL ' . $expiryDays . ' DAY' : 'NULL') . '
+              WHERE order_id = :order_id AND revoked_at IS NULL'
+         );
+         $statement->execute(['order_id' => $orderId]);
+ 
+         return $statement->rowCount();
      }
  
      public static function tokensForOrder(int $orderId): array
⋮ 15 unchanged lines ⋮
includes/download-handler.php Modified +4 -1
⋮ 72 unchanged lines ⋮
              self::fail($settings, 404, Language::get('download_not_found', 'File not found.'));
          }
  
-         $alreadyCounted = self::countedInSession((int) $file['id']);
+         $grantStarted = $grantToConsume === null || (isset($grant) && (int) ($grant['download_count'] ?? 0) > 0);
+         $alreadyCounted = self::countedInSession((int) $file['id'])
+             || (DigitalFiles::isContinuationRequest() && $grantStarted)
+             || ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'HEAD';
  
          if (!$alreadyCounted) {
              if ($grantToConsume !== null && !DigitalFiles::consumeGrant($grantToConsume)) {
⋮ 52 unchanged lines ⋮
includes/front-header.php Modified +3 -0
⋮ 54 unchanged lines ⋮
      <?php if (!empty($resolvedPageDescription)): ?>
          <meta name="description" content="<?= htmlspecialchars($resolvedPageDescription) ?>">
      <?php endif; ?>
+     <?php if (!empty($pageNoindex)): ?>
+         <meta name="robots" content="noindex, nofollow">
+     <?php endif; ?>
      <?= SiteFront::renderSeoMeta() ?>
      <?= Languages::renderAlternates() ?>
      <?= SiteFront::renderOpenGraph($resolvedPageTitle, $resolvedPageDescription, $ogType ?? 'website', $ogImagePath ?? null) ?>
⋮ 158 unchanged lines ⋮
includes/licenses.php Added +225 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/database.php';
+ 
+ final class Licenses
+ {
+     public const MODES = ['none', 'generate', 'pool'];
+     public const DEFAULT_PATTERN = 'XXXXX-XXXXX-XXXXX-XXXXX';
+     private const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
+ 
+     public static function mode(array $product): string
+     {
+         $mode = (string) ($product['license_mode'] ?? 'none');
+ 
+         return in_array($mode, self::MODES, true) ? $mode : 'none';
+     }
+ 
+     public static function sanitizePattern(string $pattern): string
+     {
+         $pattern = strtoupper(trim($pattern));
+         $pattern = (string) preg_replace('/[^A-Z0-9#\-_.]/', '', $pattern);
+         $pattern = substr($pattern, 0, 80);
+ 
+         return substr_count($pattern, 'X') + substr_count($pattern, '#') >= 8 ? $pattern : '';
+     }
+ 
+     public static function generate(string $pattern): string
+     {
+         $pattern = self::sanitizePattern($pattern);
+         if ($pattern === '') {
+             $pattern = self::DEFAULT_PATTERN;
+         }
+         $alphabetLength = strlen(self::ALPHABET);
+         $key = '';
+         foreach (str_split($pattern) as $char) {
+             if ($char === 'X') {
+                 $key .= self::ALPHABET[random_int(0, $alphabetLength - 1)];
+             } elseif ($char === '#') {
+                 $key .= (string) random_int(0, 9);
+             } else {
+                 $key .= $char;
+             }
+         }
+ 
+         return $key;
+     }
+ 
+     public static function addToPool(int $productId, string $text): array
+     {
+         $usersDb = Database::users();
+         $added = 0;
+         $skipped = 0;
+         $insert = $usersDb->prepare("INSERT IGNORE INTO license_keys (product_id, license_key, source) VALUES (:product_id, :license_key, 'pool')");
+         foreach (preg_split('/\R/', $text) ?: [] as $line) {
+             $key = trim((string) preg_replace('/[\x00-\x1F\x7F]+/', '', $line));
+             if ($key === '') {
+                 continue;
+             }
+             if (strlen($key) > 255) {
+                 $skipped++;
+                 continue;
+             }
+             $insert->execute(['product_id' => $productId, 'license_key' => $key]);
+             if ($insert->rowCount() > 0) {
+                 $added++;
+             } else {
+                 $skipped++;
+             }
+             if ($added >= 5000) {
+                 break;
+             }
+         }
+ 
+         return [$added, $skipped];
+     }
+ 
+     public static function counts(int $productId): array
+     {
+         $statement = Database::users()->prepare(
+             "SELECT
+                 SUM(CASE WHEN order_id IS NULL AND revoked_at IS NULL THEN 1 ELSE 0 END) AS available,
+                 SUM(CASE WHEN order_id IS NOT NULL AND revoked_at IS NULL THEN 1 ELSE 0 END) AS assigned,
+                 SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked
+              FROM license_keys WHERE product_id = :product_id"
+         );
+         $statement->execute(['product_id' => $productId]);
+         $row = $statement->fetch() ?: [];
+ 
+         return [
+             'available' => (int) ($row['available'] ?? 0),
+             'assigned' => (int) ($row['assigned'] ?? 0),
+             'revoked' => (int) ($row['revoked'] ?? 0),
+         ];
+     }
+ 
+     public static function recentForProduct(int $productId, int $limit = 50): array
+     {
+         $statement = Database::users()->prepare(
+             'SELECT k.*, o.order_number FROM license_keys k LEFT JOIN orders o ON o.id = k.order_id
+              WHERE k.product_id = :product_id ORDER BY (k.order_id IS NULL) ASC, k.assigned_at DESC, k.id DESC LIMIT ' . max(1, min(500, $limit))
+         );
+         $statement->execute(['product_id' => $productId]);
+ 
+         return $statement->fetchAll();
+     }
+ 
+     public static function deleteUnused(int $productId, int $keyId): bool
+     {
+         $statement = Database::users()->prepare('DELETE FROM license_keys WHERE id = :id AND product_id = :product_id AND order_id IS NULL');
+         $statement->execute(['id' => $keyId, 'product_id' => $productId]);
+ 
+         return $statement->rowCount() > 0;
+     }
+ 
+     public static function assignForOrder(array $order, array $items): array
+     {
+         $usersDb = Database::users();
+         $siteDb = Database::site();
+         $productIds = array_values(array_unique(array_map(static fn(array $item): int => (int) $item['product_id'], $items)));
+         if (empty($productIds)) {
+             return ['keys' => [], 'missing' => []];
+         }
+ 
+         $placeholders = implode(',', array_fill(0, count($productIds), '?'));
+         $productsStatement = $siteDb->prepare("SELECT id, title, license_mode, license_pattern FROM products WHERE id IN ({$placeholders})");
+         $productsStatement->execute($productIds);
+         $products = [];
+         foreach ($productsStatement->fetchAll() as $product) {
+             $products[(int) $product['id']] = $product;
+         }
+ 
+         $missing = [];
+         $userId = $order['user_account_id'] !== null ? (int) $order['user_account_id'] : null;
+ 
+         foreach ($items as $item) {
+             $product = $products[(int) $item['product_id']] ?? null;
+             if ($product === null) {
+                 continue;
+             }
+             $mode = self::mode($product);
+             if ($mode === 'none') {
+                 continue;
+             }
+             $needed = max(1, (int) $item['quantity']);
+             $haveStatement = $usersDb->prepare('SELECT COUNT(*) FROM license_keys WHERE order_item_id = :item_id');
+             $haveStatement->execute(['item_id' => (int) $item['id']]);
+             $needed -= (int) $haveStatement->fetchColumn();
+ 
+             for ($i = 0; $i < $needed; $i++) {
+                 if ($mode === 'pool') {
+                     $claim = $usersDb->prepare(
+                         'UPDATE license_keys SET order_id = :order_id, order_item_id = :item_id, user_account_id = :user_id, assigned_at = NOW()
+                          WHERE product_id = :product_id AND order_id IS NULL AND revoked_at IS NULL ORDER BY id ASC LIMIT 1'
+                     );
+                     $claim->execute(['order_id' => (int) $order['id'], 'item_id' => (int) $item['id'], 'user_id' => $userId, 'product_id' => (int) $product['id']]);
+                     if ($claim->rowCount() === 0) {
+                         $missing[(int) $product['id']] = ($missing[(int) $product['id']] ?? 0) + ($needed - $i);
+                         break;
+                     }
+                     continue;
+                 }
+ 
+                 $insert = $usersDb->prepare(
+                     "INSERT IGNORE INTO license_keys (product_id, license_key, source, order_id, order_item_id, user_account_id, assigned_at)
+                      VALUES (:product_id, :license_key, 'generated', :order_id, :item_id, :user_id, NOW())"
+                 );
+                 for ($attempt = 0; $attempt < 5; $attempt++) {
+                     $insert->execute([
+                         'product_id' => (int) $product['id'],
+                         'license_key' => self::generate((string) ($product['license_pattern'] ?? '')),
+                         'order_id' => (int) $order['id'],
+                         'item_id' => (int) $item['id'],
+                         'user_id' => $userId,
+                     ]);
+                     if ($insert->rowCount() > 0) {
+                         break;
+                     }
+                 }
+             }
+         }
+ 
+         return ['keys' => self::forOrder((int) $order['id']), 'missing' => $missing];
+     }
+ 
+     public static function forOrder(int $orderId): array
+     {
+         $statement = Database::users()->prepare(
+             'SELECT k.*, oi.product_title_snapshot FROM license_keys k LEFT JOIN order_items oi ON oi.id = k.order_item_id
+              WHERE k.order_id = :order_id AND k.revoked_at IS NULL ORDER BY k.order_item_id ASC, k.id ASC'
+         );
+         $statement->execute(['order_id' => $orderId]);
+ 
+         return $statement->fetchAll();
+     }
+ 
+     public static function forUser(int $userAccountId): array
+     {
+         $statement = Database::users()->prepare(
+             "SELECT k.*, oi.product_title_snapshot, o.order_number, o.id AS order_ref FROM license_keys k
+              JOIN orders o ON o.id = k.order_id
+              LEFT JOIN order_items oi ON oi.id = k.order_item_id
+              WHERE o.user_account_id = :user_id AND k.revoked_at IS NULL
+                AND o.status IN ('paid','processing','fulfilled','shipped','completed')
+              ORDER BY k.assigned_at DESC, k.id DESC"
+         );
+         $statement->execute(['user_id' => $userAccountId]);
+ 
+         return $statement->fetchAll();
+     }
+ 
+     public static function revokeForOrder(int $orderId): void
+     {
+         Database::users()->prepare('UPDATE license_keys SET revoked_at = NOW() WHERE order_id = :order_id AND revoked_at IS NULL')
+             ->execute(['order_id' => $orderId]);
+     }
+ 
+     public static function linkToAccount(int $orderId, int $userAccountId): void
+     {
+         Database::users()->prepare('UPDATE license_keys SET user_account_id = :user_id WHERE order_id = :order_id')
+             ->execute(['user_id' => $userAccountId, 'order_id' => $orderId]);
+     }
+ }
+ 
includes/mail-templates.php Modified +193 -4
⋮ 7 unchanged lines ⋮
  
  final class MailTemplates
  {
-     public static function orderConfirmationEmail(array $order, array $items, array $downloadLinks = []): array
+     public static function orderConfirmationEmail(array $order, array $items, array $downloadLinks = [], array $licenses = [], string $orderUrl = ''): array
      {
          $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
          $currency = (string) ($order['currency'] ?? Currency::DEFAULT_CODE);
⋮ 46 unchanged lines ⋮
              . '</table>'
              . '<table style="width:100%;border-collapse:collapse;margin:0 0 16px;">' . $summaryRows . '</table>'
              . $downloadsBlock
+             . self::licensesBlock($licenses)
              . $shippingBlock
+             . self::orderLinkBlock($orderUrl)
          );
  
          return ['subject' => $subject, 'html' => $html];
⋮ 22 unchanged lines ⋮
              '<p style="margin:0 0 16px;color:#334155;">' . self::fill(self::t('email_status_intro', 'The status of your order {order} changed to:'), '', '<strong>#' . htmlspecialchars($orderNumber, ENT_QUOTES) . '</strong>') . '</p>'
              . '<p style="margin:0 0 16px;"><span style="display:inline-block;padding:6px 14px;border-radius:999px;background:#eff6ff;color:#2563eb;font-weight:600;font-size:13.5px;">' . htmlspecialchars($statusLabel, ENT_QUOTES) . '</span></p>'
              . $trackingBlock
+             . (!empty($order['access_token']) && !empty($order['id']) ? self::orderLinkBlock(self::shopOrderUrl($order)) : '')
          );
  
          return ['subject' => $subject, 'html' => $html];
      }
  
+     public static function orderPlacedEmail(array $order, array $items, string $orderUrl = ''): array
+     {
+         $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
+         $currency = (string) ($order['currency'] ?? Currency::DEFAULT_CODE);
+         $orderNumber = (string) ($order['order_number'] ?? '');
+         $method = (string) ($order['payment_method'] ?? '');
+ 
+         $intro = $method === 'bank_transfer'
+             ? self::t('email_placed_bank_intro', 'We have received your order. It will be processed as soon as your transfer arrives.')
+             : self::t('email_placed_cod_intro', 'We have received your order. You will pay when it is delivered.');
+ 
+         $instructions = '';
+         if ($method === 'bank_transfer') {
+             require_once __DIR__ . '/shop.php';
+             $details = Shop::bankInstructions($order);
+             if ($details !== '') {
+                 $days = Shop::bankPaymentDays();
+                 $instructions = '<h3 style="margin:20px 0 8px;font-size:15px;color:#0f172a;">' . self::t('email_bank_title', 'How to pay') . '</h3>'
+                     . '<div style="padding:14px 16px;border:1px solid #e2e8f0;border-radius:10px;background:#f8fafc;color:#334155;line-height:1.6;">' . nl2br(htmlspecialchars($details, ENT_QUOTES)) . '</div>'
+                     . '<p style="margin:10px 0 0;color:#334155;">' . self::t('email_bank_title_reference', 'Please put this in the transfer title:') . ' <strong>' . htmlspecialchars($orderNumber, ENT_QUOTES) . '</strong></p>'
+                     . ($days > 0 ? '<p style="margin:6px 0 0;color:#64748b;font-size:12.5px;">' . htmlspecialchars(str_replace('{days}', (string) $days, self::raw('email_bank_days', 'Please pay within {days} days, otherwise the order may be canceled.')), ENT_QUOTES) . '</p>' : '');
+             }
+         }
+ 
+         $subject = self::fill(self::raw('email_placed_subject', 'Order received — {site} #{order}'), $siteName, $orderNumber);
+         $html = self::layout(
+             $siteName,
+             self::raw('email_placed_heading', 'Thanks for your order!'),
+             '<p style="margin:0 0 16px;color:#334155;">' . $intro . '</p>'
+             . self::itemsTable($items, $currency)
+             . '<table style="width:100%;border-collapse:collapse;margin:0 0 16px;">' . self::summaryRows($order, $currency) . '</table>'
+             . $instructions
+             . self::shippingAddressBlock($order)
+             . self::orderLinkBlock($orderUrl)
+         );
+ 
+         return ['subject' => $subject, 'html' => $html];
+     }
+ 
+     public static function adminNewOrderEmail(array $order, array $items, bool $licensesMissing = false): array
+     {
+         $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
+         $currency = (string) ($order['currency'] ?? Currency::DEFAULT_CODE);
+         $orderNumber = (string) ($order['order_number'] ?? '');
+         require_once __DIR__ . '/shop.php';
+         $paid = in_array((string) ($order['status'] ?? ''), ['paid', 'processing', 'fulfilled', 'shipped', 'completed'], true);
+         $dashboardUrl = Shop::baseUrl() . '/dashboard.php?view=order-detail&id=' . (int) $order['id'];
+ 
+         $html = self::layout(
+             $siteName,
+             $paid ? 'New paid order' : 'New order waiting for payment',
+             '<p style="margin:0 0 12px;color:#334155;">Order <strong>#' . htmlspecialchars($orderNumber, ENT_QUOTES) . '</strong> · '
+             . htmlspecialchars(Shop::paymentLabel((string) ($order['payment_method'] ?? 'card')), ENT_QUOTES) . ' · '
+             . htmlspecialchars(Currency::format((int) ($order['total_cents'] ?? 0), $currency), ENT_QUOTES) . '</p>'
+             . ($licensesMissing ? '<p style="margin:0 0 12px;padding:10px 12px;border-radius:8px;background:#fef2f2;color:#b91c1c;">There were not enough license keys for this order. Add keys to the product and send them again from the order page.</p>' : '')
+             . self::itemsTable($items, $currency)
+             . self::shippingAddressBlock($order)
+             . '<p style="margin:20px 0 0;"><a href="' . htmlspecialchars($dashboardUrl, ENT_QUOTES) . '" style="display:inline-block;padding:10px 16px;border-radius:8px;background:#0f172a;color:#ffffff;text-decoration:none;font-weight:600;">Open the order</a></p>'
+         );
+ 
+         return ['subject' => ($paid ? 'New order' : 'New order (awaiting payment)') . ' #' . $orderNumber . ' — ' . $siteName, 'html' => $html];
+     }
+ 
+     public static function lowStockEmail(array $products): array
+     {
+         $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
+         require_once __DIR__ . '/shop.php';
+         $rows = '';
+         foreach ($products as $product) {
+             $rows .= '<li style="margin:0 0 6px;"><a href="' . htmlspecialchars(Shop::baseUrl() . '/dashboard.php?view=product-edit&id=' . (int) $product['id'], ENT_QUOTES) . '" style="color:#2563eb;">'
+                 . htmlspecialchars((string) $product['title'], ENT_QUOTES) . '</a> — ' . (int) $product['stock'] . ' left</li>';
+         }
+         $html = self::layout($siteName, 'Running low on stock', '<p style="margin:0 0 12px;color:#334155;">These products are almost sold out:</p><ul style="margin:0;padding-left:18px;">' . $rows . '</ul>');
+ 
+         return ['subject' => 'Low stock — ' . $siteName, 'html' => $html];
+     }
+ 
+     public static function passwordResetEmail(string $resetUrl): array
+     {
+         $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
+         $html = self::layout(
+             $siteName,
+             self::raw('email_reset_heading', 'Reset your password'),
+             '<p style="margin:0 0 16px;color:#334155;">' . self::t('email_reset_intro', 'Someone asked to reset the password for your account. If it was you, click the button below. The link works for one hour.') . '</p>'
+             . self::buttonBlock($resetUrl, self::raw('email_reset_button', 'Set a new password'))
+             . '<p style="margin:16px 0 0;color:#64748b;font-size:12.5px;">' . self::t('email_reset_ignore', 'If you did not ask for this, you can ignore this email. Your password stays the same.') . '</p>'
+         );
+ 
+         return ['subject' => self::fill(self::raw('email_reset_subject', 'Reset your password — {site}'), $siteName, ''), 'html' => $html];
+     }
+ 
+     public static function verifyEmail(string $verifyUrl): array
+     {
+         $siteName = (string) (SiteFront::settings()['site_name'] ?? 'Our store');
+         $html = self::layout(
+             $siteName,
+             self::raw('email_verify_heading', 'Confirm your email'),
+             '<p style="margin:0 0 16px;color:#334155;">' . self::t('email_verify_intro', 'Please confirm this is your email address. After that, orders you placed as a guest with this email show up in your account.') . '</p>'
+             . self::buttonBlock($verifyUrl, self::raw('email_verify_button', 'Confirm email'))
+         );
+ 
+         return ['subject' => self::fill(self::raw('email_verify_subject', 'Confirm your email — {site}'), $siteName, ''), 'html' => $html];
+     }
+ 
+     private static function itemsTable(array $items, string $currency): string
+     {
+         $rows = '';
+         foreach ($items as $item) {
+             $variant = (string) ($item['variant_name_snapshot'] ?? '');
+             $rows .= '<tr>'
+                 . '<td style="padding:10px 0;border-bottom:1px solid #e2e8f0;">' . htmlspecialchars((string) ($item['product_title_snapshot'] ?? ''), ENT_QUOTES)
+                 . ($variant !== '' ? '<br><span style="color:#64748b;font-size:12.5px;">' . htmlspecialchars($variant, ENT_QUOTES) . '</span>' : '')
+                 . '</td>'
+                 . '<td style="padding:10px 0;border-bottom:1px solid #e2e8f0;text-align:center;">' . (int) ($item['quantity'] ?? 1) . '</td>'
+                 . '<td style="padding:10px 0;border-bottom:1px solid #e2e8f0;text-align:right;">' . htmlspecialchars(Currency::format((int) ($item['total_cents'] ?? 0), $currency), ENT_QUOTES) . '</td>'
+                 . '</tr>';
+         }
+ 
+         return '<table style="width:100%;border-collapse:collapse;margin:16px 0;">'
+             . '<thead><tr>'
+             . '<th style="text-align:left;padding:8px 0;border-bottom:2px solid #0f172a;color:#0f172a;">' . self::t('email_column_item', 'Item') . '</th>'
+             . '<th style="text-align:center;padding:8px 0;border-bottom:2px solid #0f172a;color:#0f172a;">' . self::t('email_column_qty', 'Qty') . '</th>'
+             . '<th style="text-align:right;padding:8px 0;border-bottom:2px solid #0f172a;color:#0f172a;">' . self::t('cart_total', 'Total') . '</th>'
+             . '</tr></thead><tbody>' . $rows . '</tbody></table>';
+     }
+ 
+     private static function licensesBlock(array $licenses): string
+     {
+         if (empty($licenses)) {
+             return '';
+         }
+         $rows = '';
+         foreach ($licenses as $license) {
+             $rows .= '<li style="margin:0 0 8px;">'
+                 . htmlspecialchars((string) ($license['product_title_snapshot'] ?? ''), ENT_QUOTES)
+                 . '<br><code style="display:inline-block;margin-top:3px;padding:4px 8px;border-radius:6px;background:#f1f5f9;color:#0f172a;font-size:13.5px;letter-spacing:.03em;">'
+                 . htmlspecialchars((string) $license['license_key'], ENT_QUOTES) . '</code></li>';
+         }
+ 
+         return '<h3 style="margin:24px 0 8px;font-size:15px;color:#0f172a;">' . self::t('email_licenses_title', 'Your license keys') . '</h3>'
+             . '<ul style="margin:0 0 8px;padding-left:18px;">' . $rows . '</ul>';
+     }
+ 
+     private static function shopOrderUrl(array $order): string
+     {
+         require_once __DIR__ . '/shop.php';
+ 
+         return Shop::orderUrl($order);
+     }
+ 
+     private static function orderLinkBlock(string $orderUrl): string
+     {
+         if ($orderUrl === '') {
+             return '';
+         }
+ 
+         return '<div style="margin-top:24px;">' . self::buttonBlock($orderUrl, self::raw('email_view_order', 'View your order')) . '</div>';
+     }
+ 
+     private static function buttonBlock(string $url, string $label): string
+     {
+         return '<p style="margin:0;"><a href="' . htmlspecialchars($url, ENT_QUOTES) . '" style="display:inline-block;padding:11px 18px;border-radius:8px;background:#2563eb;color:#ffffff;text-decoration:none;font-weight:600;">'
+             . htmlspecialchars($label, ENT_QUOTES) . '</a></p>'
+             . '<p style="margin:8px 0 0;color:#94a3b8;font-size:11.5px;word-break:break-all;">' . htmlspecialchars($url, ENT_QUOTES) . '</p>';
+     }
+ 
+     private static function taxLabel(array $order): string
+     {
+         require_once __DIR__ . '/shop.php';
+         $label = Shop::taxLabel();
+         $rate = (int) ($order['tax_rate_bp'] ?? 0);
+         if ($rate > 0) {
+             $label .= ' ' . Shop::formatRate($rate);
+         }
+         if ((int) ($order['prices_include_tax'] ?? 0) === 1) {
+             $label .= ' (' . self::raw('cart_tax_included', 'included') . ')';
+         }
+ 
+         return $label;
+     }
+ 
      private static function statusLabel(string $status): string
      {
          return self::raw('order_status_' . $status, ucfirst($status));
⋮ 28 unchanged lines ⋮
          if ((int) ($order['discount_cents'] ?? 0) > 0) {
              $line(self::raw('cart_discount', 'Discount'), -(int) $order['discount_cents'], $currency);
          }
-         if ((int) ($order['shipping_cents'] ?? 0) > 0) {
-             $line(self::raw('order_shipping_label', 'Shipping'), (int) $order['shipping_cents'], $currency);
+         if ((int) ($order['shipping_cents'] ?? 0) > 0 || !empty($order['shipping_method'])) {
+             $shippingLabel = self::raw('order_shipping_label', 'Shipping') . (!empty($order['shipping_method']) ? ' (' . $order['shipping_method'] . ')' : '');
+             $line($shippingLabel, (int) ($order['shipping_cents'] ?? 0), $currency);
          }
+         if ((int) ($order['cod_fee_cents'] ?? 0) > 0) {
+             $line(self::raw('order_cod_fee_label', 'Cash on delivery fee'), (int) $order['cod_fee_cents'], $currency);
+         }
          if ((int) ($order['tax_cents'] ?? 0) > 0) {
-             $line(self::raw('email_tax', 'Tax'), (int) $order['tax_cents'], $currency);
+             $taxLabel = self::taxLabel($order);
+             $line($taxLabel, (int) $order['tax_cents'], $currency);
          }
  
          $rows .= '<tr>'
⋮ 54 unchanged lines ⋮
includes/order-view.php Added +246 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/orders.php';
+ require_once __DIR__ . '/shop.php';
+ require_once __DIR__ . '/currency.php';
+ require_once __DIR__ . '/language.php';
+ require_once __DIR__ . '/icons.php';
+ 
+ final class OrderView
+ {
+     public static function statusLabel(string $status): string
+     {
+         return Language::get('order_status_' . $status, ucfirst($status));
+     }
+ 
+     public static function render(array $order, array $items, bool $viewerOwnsAccountOrder): string
+     {
+         $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+         $currency = (string) $order['currency'];
+         $status = (string) $order['status'];
+         $isPaid = in_array($status, Orders::PAID_STATUSES, true);
+         $method = (string) ($order['payment_method'] ?? '');
+         if ($method === '') {
+             $method = in_array((string) ($order['provider'] ?? ''), ['stripe', 'polar'], true) ? 'card' : (string) ($order['provider'] ?? '');
+         }
+ 
+         $html = '<div class="order-view">';
+         $html .= '<div class="order-view-head">';
+         $html .= '<div><span class="order-view-label">' . $e(Language::get('order_number_label', 'Order number')) . '</span><strong>' . $e($order['order_number']) . '</strong></div>';
+         $html .= '<div><span class="order-view-label">' . $e(Language::get('order_placed_label', 'Placed on')) . '</span>' . $e(self::date((string) $order['created_at'])) . '</div>';
+         $html .= '<div><span class="order-view-label">' . $e(Language::get('order_status_label', 'Status')) . '</span><span class="status-pill status-' . $e($status) . '">' . $e(self::statusLabel($status)) . '</span></div>';
+         if ($method !== '') {
+             $html .= '<div><span class="order-view-label">' . $e(Language::get('order_payment_label', 'Payment')) . '</span>' . $e(Shop::paymentLabel($method)) . '</div>';
+         }
+         $html .= '</div>';
+ 
+         if ($status === 'pending' && $method === 'bank_transfer') {
+             $details = Shop::bankInstructions($order);
+             $html .= '<div class="order-notice order-notice-info">'
+                 . '<h3>' . $e(Language::get('order_bank_title', 'Waiting for your bank transfer')) . '</h3>'
+                 . '<p>' . $e(Language::get('order_bank_intro', 'Send the amount below to this account. We will process your order as soon as the money arrives.')) . '</p>'
+                 . '<dl class="order-bank">'
+                 . '<dt>' . $e(Language::get('order_bank_amount', 'Amount')) . '</dt><dd>' . $e(Currency::format((int) $order['total_cents'], $currency)) . '</dd>'
+                 . '<dt>' . $e(Language::get('order_bank_reference', 'Transfer title')) . '</dt><dd><code>' . $e($order['order_number']) . '</code></dd>'
+                 . '</dl>'
+                 . ($details !== '' ? '<div class="order-bank-details">' . nl2br($e($details)) . '</div>' : '')
+                 . '</div>';
+         } elseif ($status === 'pending' && $method === 'cod') {
+             $html .= '<div class="order-notice order-notice-info"><p>' . $e(Language::get('order_cod_note', 'You will pay when the parcel is delivered.')) . ' <strong>' . $e(Currency::format((int) $order['total_cents'], $currency)) . '</strong></p></div>';
+         } elseif ($status === 'pending') {
+             $html .= '<div class="order-notice order-notice-info"><p>' . $e(Language::get('order_confirmation_processing', 'Your payment is still being processed. This page will show your final order status once confirmed — you will also receive a confirmation email.')) . '</p></div>';
+         } elseif ($status === 'failed') {
+             $html .= '<div class="order-notice order-notice-error"><p>' . $e(Language::get('order_failed_note', 'The payment did not go through, so the order was not placed. You can try again from your cart.')) . '</p></div>';
+         }
+ 
+         if (!empty($order['tracking_number'])) {
+             $tracking = !empty($order['tracking_url'])
+                 ? '<a href="' . $e($order['tracking_url']) . '" target="_blank" rel="noopener noreferrer">' . $e($order['tracking_number']) . '</a>'
+                 : $e($order['tracking_number']);
+             $html .= '<p class="order-tracking">' . Icons::icon('map-pin', 'icon icon-sm') . $e(Language::get('order_tracking_label', 'Tracking')) . ': ' . $tracking . '</p>';
+         }
+ 
+         $html .= '<table class="order-items"><thead><tr><th>' . $e(Language::get('cart_column_product', 'Product')) . '</th><th>' . $e(Language::get('cart_column_quantity', 'Quantity')) . '</th><th>' . $e(Language::get('cart_column_total', 'Total')) . '</th></tr></thead><tbody>';
+         foreach ($items as $item) {
+             $html .= '<tr><td>' . $e($item['product_title_snapshot'])
+                 . ($item['variant_name_snapshot'] !== null ? '<small>' . $e($item['variant_name_snapshot']) . '</small>' : '')
+                 . '</td><td>' . (int) $item['quantity'] . '</td><td>' . $e(Currency::format((int) $item['total_cents'], $currency)) . '</td></tr>';
+         }
+         $html .= '</tbody></table>';
+ 
+         $html .= '<div class="order-totals">' . self::totals($order) . '</div>';
+ 
+         if ($isPaid) {
+             $html .= self::downloads($order, $items, $viewerOwnsAccountOrder);
+             $html .= self::licenses((int) $order['id']);
+         } elseif (self::orderHasDownloads($items) && $status === 'pending') {
+             $html .= '<p class="order-hint">' . $e(Language::get('order_downloads_pending', 'Your download links will appear here and be emailed to you as soon as the payment is confirmed. Refresh this page in a moment.')) . '</p>';
+         }
+ 
+         $shipping = Shop::addressLines($order, 'shipping');
+         $billing = Shop::addressLines($order, 'billing');
+         if (!empty($shipping) || !empty($billing)) {
+             $html .= '<div class="order-addresses">';
+             if (!empty($shipping)) {
+                 $html .= '<div><h3>' . $e(Language::get('checkout_shipping_title', 'Shipping address')) . '</h3><p>' . implode('<br>', array_map($e, $shipping))
+                     . (!empty($order['shipping_method']) ? '<br><small>' . $e($order['shipping_method']) . '</small>' : '') . '</p></div>';
+             }
+             $showBilling = !empty($billing) && (
+                 (int) ($order['billing_same_as_shipping'] ?? 1) !== 1
+                 || empty($shipping)
+                 || !empty($order['billing_tax_id'])
+                 || !empty($order['billing_company'])
+             );
+             if ($showBilling) {
+                 $html .= '<div><h3>' . $e(Language::get('checkout_billing_title', 'Billing details')) . '</h3><p>' . implode('<br>', array_map($e, $billing)) . '</p></div>';
+             }
+             $html .= '</div>';
+         }
+ 
+         $history = Orders::history((int) $order['id']);
+         if (count($history) > 1) {
+             $html .= '<h3 class="order-section-title">' . $e(Language::get('order_history_title', 'What happened')) . '</h3><ol class="order-timeline">';
+             $previous = null;
+             foreach ($history as $entry) {
+                 if ($entry['status'] === $previous) {
+                     continue;
+                 }
+                 $previous = $entry['status'];
+                 $html .= '<li><span class="status-pill status-' . $e($entry['status']) . '">' . $e(self::statusLabel((string) $entry['status'])) . '</span><time>' . $e(self::date((string) $entry['created_at'], true)) . '</time></li>';
+             }
+             $html .= '</ol>';
+         }
+ 
+         if ($isPaid || $status === 'refunded') {
+             $html .= '<p class="order-actions"><a class="order-button" href="' . $e(Shop::receiptUrl($order)) . '" target="_blank" rel="noopener">' . Icons::icon('download', 'icon icon-sm') . $e(Language::get('order_receipt_button', 'Receipt')) . '</a></p>';
+         }
+ 
+         return $html . '</div>';
+     }
+ 
+     public static function totals(array $order): string
+     {
+         $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+         $currency = (string) $order['currency'];
+         $row = static fn(string $label, string $amount, string $class = ''): string => '<div class="cart-summary-row' . ($class !== '' ? ' ' . $class : '') . '"><span>' . $e($label) . '</span><span>' . $e($amount) . '</span></div>';
+ 
+         $html = $row(Language::get('cart_subtotal', 'Subtotal'), Currency::format((int) $order['subtotal_cents'], $currency));
+         if ((int) $order['discount_cents'] > 0) {
+             $html .= $row(Language::get('cart_discount', 'Discount') . (!empty($order['discount_code']) ? ' (' . $order['discount_code'] . ')' : ''), '-' . Currency::format((int) $order['discount_cents'], $currency));
+         }
+         if ((int) $order['shipping_cents'] > 0 || !empty($order['shipping_method'])) {
+             $html .= $row(Language::get('order_shipping_label', 'Shipping'), (int) $order['shipping_cents'] === 0 ? Language::get('checkout_shipping_free', 'Free') : Currency::format((int) $order['shipping_cents'], $currency));
+         }
+         if ((int) ($order['cod_fee_cents'] ?? 0) > 0) {
+             $html .= $row(Language::get('order_cod_fee_label', 'Cash on delivery fee'), Currency::format((int) $order['cod_fee_cents'], $currency));
+         }
+         if ((int) $order['tax_cents'] > 0) {
+             $label = Shop::taxLabel() . ((int) ($order['tax_rate_bp'] ?? 0) > 0 ? ' ' . Shop::formatRate((int) $order['tax_rate_bp']) : '')
+                 . ((int) ($order['prices_include_tax'] ?? 0) === 1 ? ' (' . Language::get('cart_tax_included', 'included') . ')' : '');
+             $html .= $row($label, Currency::format((int) $order['tax_cents'], $currency));
+         }
+ 
+         return $html . $row(Language::get('cart_total', 'Total'), Currency::format((int) $order['total_cents'], $currency), 'cart-summary-total');
+     }
+ 
+     private static function orderHasDownloads(array $items): bool
+     {
+         foreach (array_unique(array_map(static fn(array $item): int => (int) $item['product_id'], $items)) as $productId) {
+             if (!empty(DigitalFiles::filesForProduct($productId))) {
+                 return true;
+             }
+         }
+ 
+         return false;
+     }
+ 
+     private static function downloads(array $order, array $items, bool $viewerOwnsAccountOrder): string
+     {
+         $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+         $grants = DigitalFiles::grantRowsForOrder((int) $order['id']);
+         $groups = '';
+ 
+         foreach (array_unique(array_map(static fn(array $item): int => (int) $item['product_id'], $items)) as $productId) {
+             $files = DigitalFiles::filesForProduct($productId);
+             if (empty($files)) {
+                 continue;
+             }
+             $grant = $grants[$productId] ?? null;
+             $token = $viewerOwnsAccountOrder ? null : ($grant['token'] ?? null);
+             if (!$viewerOwnsAccountOrder && $token === null) {
+                 continue;
+             }
+ 
+             $limit = '';
+             if ($viewerOwnsAccountOrder) {
+                 $limit = Language::get('order_downloads_unlimited', 'No limit while you are logged in.');
+             } elseif ($grant !== null) {
+                 $parts = [];
+                 if ($grant['max_downloads'] !== null) {
+                     $left = max(0, (int) $grant['max_downloads'] - (int) $grant['download_count']);
+                     $parts[] = str_replace('{count}', (string) $left, Language::get('order_downloads_left', '{count} downloads left'));
+                 }
+                 if (!empty($grant['expires_at'])) {
+                     $parts[] = str_replace('{date}', self::date((string) $grant['expires_at']), Language::get('order_downloads_until', 'link works until {date}'));
+                 }
+                 $limit = implode(' · ', $parts);
+             }
+ 
+             $title = '';
+             foreach ($items as $item) {
+                 if ((int) $item['product_id'] === $productId) {
+                     $title = (string) $item['product_title_snapshot'];
+                     break;
+                 }
+             }
+ 
+             $groups .= '<div class="download-group"><h4>' . $e($title) . '</h4><ul class="download-list">';
+             foreach ($files as $file) {
+                 $groups .= '<li><a href="' . $e(DigitalFiles::downloadUrl((int) $file['id'], $token)) . '" rel="nofollow">' . Icons::icon('download', 'icon icon-sm') . $e(DigitalFiles::displayName($file)) . '</a>'
+                     . '<small>' . $e(DigitalFiles::formatSize((int) $file['size_bytes'])) . '</small></li>';
+             }
+             $groups .= '</ul>' . ($limit !== '' ? '<p class="order-hint">' . $e($limit) . '</p>' : '') . '</div>';
+         }
+ 
+         if ($groups === '') {
+             return '';
+         }
+ 
+         return '<h3 class="order-section-title">' . $e(Language::get('order_downloads_title', 'Your downloads')) . '</h3>' . $groups;
+     }
+ 
+     private static function licenses(int $orderId): string
+     {
+         $keys = Licenses::forOrder($orderId);
+         if (empty($keys)) {
+             return '';
+         }
+         $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+         $html = '<h3 class="order-section-title">' . $e(Language::get('order_licenses_title', 'License keys')) . '</h3><ul class="license-list">';
+         foreach ($keys as $key) {
+             $html .= '<li><span>' . $e($key['product_title_snapshot'] ?? '') . '</span>'
+                 . '<code class="license-key">' . $e($key['license_key']) . '</code>'
+                 . '<button type="button" class="license-copy" data-copy="' . $e($key['license_key']) . '" data-copied="' . $e(Language::get('code_copied', 'Copied')) . '">' . $e(Language::get('code_copy', 'Copy')) . '</button></li>';
+         }
+ 
+         return $html . '</ul>';
+     }
+ 
+     public static function date(string $value, bool $withTime = false): string
+     {
+         $timestamp = strtotime($value);
+         if ($timestamp === false) {
+             return $value;
+         }
+ 
+         return date($withTime ? 'Y-m-d H:i' : 'Y-m-d', $timestamp);
+     }
+ 
+     public static function copyScript(): string
+     {
+         return '<script>document.addEventListener("click",function(e){var b=e.target.closest(".license-copy");if(!b||!navigator.clipboard){return;}navigator.clipboard.writeText(b.dataset.copy).then(function(){var t=b.textContent;b.textContent=b.dataset.copied;setTimeout(function(){b.textContent=t;},1500);});});</script>';
+     }
+ }
+ 
includes/orders.php Added +473 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/database.php';
+ require_once __DIR__ . '/site-front.php';
+ require_once __DIR__ . '/shop.php';
+ require_once __DIR__ . '/digital-files.php';
+ require_once __DIR__ . '/licenses.php';
+ 
+ final class Orders
+ {
+     public const PAID_STATUSES = ['paid', 'processing', 'fulfilled', 'shipped', 'completed'];
+     public const CLOSED_STATUSES = ['canceled', 'refunded', 'failed'];
+ 
+     public static function find(int $orderId): ?array
+     {
+         if ($orderId <= 0) {
+             return null;
+         }
+         $statement = Database::users()->prepare('SELECT * FROM orders WHERE id = :id LIMIT 1');
+         $statement->execute(['id' => $orderId]);
+ 
+         return $statement->fetch() ?: null;
+     }
+ 
+     public static function items(int $orderId): array
+     {
+         $statement = Database::users()->prepare('SELECT * FROM order_items WHERE order_id = :id ORDER BY id ASC');
+         $statement->execute(['id' => $orderId]);
+ 
+         return $statement->fetchAll();
+     }
+ 
+     public static function history(int $orderId): array
+     {
+         $statement = Database::users()->prepare('SELECT * FROM order_status_history WHERE order_id = :id ORDER BY created_at ASC, id ASC');
+         $statement->execute(['id' => $orderId]);
+ 
+         return $statement->fetchAll();
+     }
+ 
+     public static function findWithToken(int $orderId, string $token): ?array
+     {
+         $token = strtolower(trim($token));
+         if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
+             return null;
+         }
+         $order = self::find($orderId);
+         if ($order === null || empty($order['access_token']) || !hash_equals((string) $order['access_token'], $token)) {
+             return null;
+         }
+ 
+         return $order;
+     }
+ 
+     public static function ensureAccessToken(array $order): array
+     {
+         if (!empty($order['access_token'])) {
+             return $order;
+         }
+         $token = bin2hex(random_bytes(32));
+         $update = Database::users()->prepare('UPDATE orders SET access_token = :token WHERE id = :id AND access_token IS NULL');
+         $update->execute(['token' => $token, 'id' => (int) $order['id']]);
+         if ($update->rowCount() > 0) {
+             $order['access_token'] = $token;
+ 
+             return $order;
+         }
+ 
+         return self::find((int) $order['id']) ?? $order;
+     }
+ 
+     public static function customerEmail(array $order): ?string
+     {
+         if ($order['user_account_id'] !== null) {
+             $statement = Database::users()->prepare('SELECT email FROM user_accounts WHERE id = :id LIMIT 1');
+             $statement->execute(['id' => (int) $order['user_account_id']]);
+             $email = (string) $statement->fetchColumn();
+             if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
+                 return $email;
+             }
+         }
+         $guest = (string) ($order['guest_email'] ?? '');
+ 
+         return $guest !== '' && filter_var($guest, FILTER_VALIDATE_EMAIL) ? $guest : null;
+     }
+ 
+     public static function addHistory(int $orderId, string $status, ?string $note = null, ?int $staffId = null): void
+     {
+         Database::users()->prepare(
+             'INSERT INTO order_status_history (order_id, status, note, changed_by_team_account_id) VALUES (:order_id, :status, :note, :staff_id)'
+         )->execute([
+             'order_id' => $orderId,
+             'status' => $status,
+             'note' => $note !== null ? mb_substr($note, 0, 500) : null,
+             'staff_id' => $staffId,
+         ]);
+     }
+ 
+     public static function reserveStock(int $orderId): void
+     {
+         $order = self::find($orderId);
+         if ($order === null || (int) ($order['stock_reserved'] ?? 0) === 1) {
+             return;
+         }
+         $claim = Database::users()->prepare('UPDATE orders SET stock_reserved = 1 WHERE id = :id AND stock_reserved = 0');
+         $claim->execute(['id' => $orderId]);
+         if ($claim->rowCount() === 0) {
+             return;
+         }
+         $lowStock = [];
+         self::adjustStock(self::items($orderId), -1, $lowStock);
+         self::alertLowStock($lowStock);
+     }
+ 
+     public static function markPaid(int $orderId, array $payment = [], string $note = 'Payment confirmed', ?int $staffId = null, ?string $finalStatus = null): bool
+     {
+         $usersDb = Database::users();
+         $update = $usersDb->prepare(
+             "UPDATE orders SET status = 'paid', paid_at = COALESCE(paid_at, NOW()), canceled_at = NULL,
+                 provider = COALESCE(:provider, provider),
+                 provider_checkout_id = COALESCE(:checkout_id, provider_checkout_id),
+                 provider_payment_id = COALESCE(:payment_id, provider_payment_id),
+                 provider_customer_id = COALESCE(:customer_id, provider_customer_id)
+              WHERE id = :id AND status IN ('pending', 'failed')"
+         );
+         $update->execute([
+             'provider' => self::nullable($payment['provider'] ?? null),
+             'checkout_id' => self::nullable($payment['checkout_id'] ?? null),
+             'payment_id' => self::nullable($payment['payment_id'] ?? null),
+             'customer_id' => self::nullable($payment['customer_id'] ?? null),
+             'id' => $orderId,
+         ]);
+         if ($update->rowCount() === 0) {
+             return false;
+         }
+ 
+         self::addHistory($orderId, 'paid', $note, $staffId);
+ 
+         $order = self::ensureAccessToken(self::find($orderId) ?? []);
+         $items = self::items($orderId);
+         $siteDb = Database::site();
+ 
+         $lowStock = [];
+         $claim = $usersDb->prepare('UPDATE orders SET stock_reserved = 1 WHERE id = :id AND stock_reserved = 0');
+         $claim->execute(['id' => $orderId]);
+         if ($claim->rowCount() > 0) {
+             self::adjustStock($items, -1, $lowStock);
+         }
+ 
+         foreach ($items as $item) {
+             $siteDb->prepare('UPDATE products SET sales_count = sales_count + :qty WHERE id = :id')
+                 ->execute(['qty' => (int) $item['quantity'], 'id' => (int) $item['product_id']]);
+         }
+ 
+         if (!empty($order['discount_code'])) {
+             $siteDb->prepare('UPDATE discounts SET times_redeemed = times_redeemed + 1 WHERE UPPER(code) = UPPER(:code)')
+                 ->execute(['code' => $order['discount_code']]);
+         }
+ 
+         self::assignInvoiceNumber($orderId);
+ 
+         $downloadLinks = [];
+         try {
+             $downloadLinks = DigitalFiles::grantsForOrder($usersDb, $order, $items);
+         } catch (Throwable $exception) {
+             error_log('StocketBase: could not create download access for order ' . $orderId . ': ' . $exception->getMessage());
+         }
+ 
+         $licenseResult = ['keys' => [], 'missing' => []];
+         try {
+             $licenseResult = Licenses::assignForOrder($order, $items);
+         } catch (Throwable $exception) {
+             error_log('StocketBase: could not assign license keys for order ' . $orderId . ': ' . $exception->getMessage());
+         }
+         if (!empty($licenseResult['missing'])) {
+             self::addHistory($orderId, 'paid', 'Not enough license keys in the pool. Add keys and use "Send keys again".', null);
+         }
+ 
+         if ($finalStatus !== null && $finalStatus !== 'paid' && in_array($finalStatus, self::PAID_STATUSES, true)) {
+             $usersDb->prepare('UPDATE orders SET status = :status WHERE id = :id')->execute(['status' => $finalStatus, 'id' => $orderId]);
+             self::addHistory($orderId, $finalStatus, null, $staffId);
+         }
+ 
+         $order = self::find($orderId) ?? $order;
+ 
+         self::mailSafely(function () use ($order, $items, $downloadLinks, $licenseResult): void {
+             $email = self::customerEmail($order);
+             if ($email !== null) {
+                 $message = MailTemplates::orderConfirmationEmail($order, $items, $downloadLinks, $licenseResult['keys'], Shop::orderUrl($order));
+                 Mailer::send($email, $message['subject'], $message['html']);
+             }
+         });
+         self::notifyAdmin($order, $items, !empty($licenseResult['missing']));
+         self::alertLowStock($lowStock);
+ 
+         return true;
+     }
+ 
+     public static function close(int $orderId, string $status, ?string $note = null, ?int $staffId = null, bool $restock = true): bool
+     {
+         if (!in_array($status, self::CLOSED_STATUSES, true)) {
+             return false;
+         }
+         $order = self::find($orderId);
+         if ($order === null || $order['status'] === $status) {
+             return false;
+         }
+ 
+         $usersDb = Database::users();
+         $usersDb->prepare('UPDATE orders SET status = :status, canceled_at = COALESCE(canceled_at, NOW()), updated_at = NOW() WHERE id = :id')
+             ->execute(['status' => $status, 'id' => $orderId]);
+         self::addHistory($orderId, $status, $note, $staffId);
+ 
+         DigitalFiles::revokeGrantsForOrder($orderId);
+         Licenses::revokeForOrder($orderId);
+ 
+         if ($restock && (int) ($order['stock_reserved'] ?? 0) === 1) {
+             $release = $usersDb->prepare('UPDATE orders SET stock_reserved = 0 WHERE id = :id AND stock_reserved = 1');
+             $release->execute(['id' => $orderId]);
+             if ($release->rowCount() > 0) {
+                 $ignored = [];
+                 self::adjustStock(self::items($orderId), 1, $ignored);
+             }
+         }
+ 
+         if (in_array($order['status'], self::PAID_STATUSES, true)) {
+             foreach (self::items($orderId) as $item) {
+                 Database::site()->prepare('UPDATE products SET sales_count = GREATEST(0, CAST(sales_count AS SIGNED) - :qty) WHERE id = :id')
+                     ->execute(['qty' => (int) $item['quantity'], 'id' => (int) $item['product_id']]);
+             }
+         }
+ 
+         return true;
+     }
+ 
+     public static function resendConfirmation(int $orderId): bool
+     {
+         $order = self::find($orderId);
+         if ($order === null || !in_array($order['status'], self::PAID_STATUSES, true)) {
+             return false;
+         }
+         $order = self::ensureAccessToken($order);
+         $items = self::items($orderId);
+         $email = self::customerEmail($order);
+         if ($email === null) {
+             return false;
+         }
+ 
+         $usersDb = Database::users();
+         $downloadLinks = DigitalFiles::grantsForOrder($usersDb, $order, $items);
+         $licenseResult = Licenses::assignForOrder($order, $items);
+         $message = MailTemplates::orderConfirmationEmail($order, $items, $downloadLinks, $licenseResult['keys'], Shop::orderUrl($order));
+ 
+         return self::loadMailer() && Mailer::send($email, $message['subject'], $message['html']);
+     }
+ 
+     public static function sendAwaitingPayment(array $order, array $items): void
+     {
+         $order = self::ensureAccessToken($order);
+         self::mailSafely(function () use ($order, $items): void {
+             $email = self::customerEmail($order);
+             if ($email !== null) {
+                 $message = MailTemplates::orderPlacedEmail($order, $items, Shop::orderUrl($order));
+                 Mailer::send($email, $message['subject'], $message['html']);
+             }
+         });
+         self::notifyAdmin($order, $items, false);
+     }
+ 
+     public static function claimGuestOrders(int $userAccountId, string $email): int
+     {
+         $email = strtolower(trim($email));
+         if ($email === '') {
+             return 0;
+         }
+         $usersDb = Database::users();
+         $statement = $usersDb->prepare('SELECT id FROM orders WHERE user_account_id IS NULL AND LOWER(guest_email) = :email');
+         $statement->execute(['email' => $email]);
+         $orderIds = array_map('intval', $statement->fetchAll(PDO::FETCH_COLUMN));
+         foreach ($orderIds as $orderId) {
+             $usersDb->prepare('UPDATE orders SET user_account_id = :user_id WHERE id = :id AND user_account_id IS NULL')
+                 ->execute(['user_id' => $userAccountId, 'id' => $orderId]);
+             $usersDb->prepare('UPDATE download_grants SET user_account_id = :user_id WHERE order_id = :id AND user_account_id IS NULL')
+                 ->execute(['user_id' => $userAccountId, 'id' => $orderId]);
+             Licenses::linkToAccount($orderId, $userAccountId);
+         }
+ 
+         return count($orderIds);
+     }
+ 
+     public static function stockProblems(array $items): array
+     {
+         $problems = [];
+         foreach ($items as $item) {
+             if (empty($item['track_inventory']) || $item['stock_quantity'] === null) {
+                 continue;
+             }
+             if ((int) $item['quantity'] > (int) $item['stock_quantity']) {
+                 $problems[] = $item['title'] . ($item['variant_name'] !== null ? ' — ' . $item['variant_name'] : '');
+             }
+         }
+ 
+         return $problems;
+     }
+ 
+     private static function adjustStock(array $items, int $direction, array &$lowStock): void
+     {
+         $siteDb = Database::site();
+         foreach ($items as $item) {
+             $productId = (int) $item['product_id'];
+             $variantId = $item['variant_id'] !== null ? (int) $item['variant_id'] : null;
+             $quantity = max(0, (int) $item['quantity']);
+             if ($quantity === 0) {
+                 continue;
+             }
+ 
+             $productStatement = $siteDb->prepare('SELECT track_inventory FROM products WHERE id = :id LIMIT 1');
+             $productStatement->execute(['id' => $productId]);
+             if ((int) $productStatement->fetchColumn() !== 1) {
+                 continue;
+             }
+ 
+             $expression = $direction < 0 ? 'GREATEST(0, stock_quantity - :qty)' : 'stock_quantity + :qty';
+             $variantUpdated = 0;
+             if ($variantId !== null) {
+                 $variantUpdate = $siteDb->prepare('UPDATE product_variants SET stock_quantity = ' . $expression . ' WHERE id = :id AND stock_quantity IS NOT NULL');
+                 $variantUpdate->execute(['qty' => $quantity, 'id' => $variantId]);
+                 $variantUpdated = $variantUpdate->rowCount();
+             }
+             if ($variantUpdated === 0) {
+                 $siteDb->prepare('UPDATE products SET stock_quantity = ' . $expression . ' WHERE id = :id AND stock_quantity IS NOT NULL')
+                     ->execute(['qty' => $quantity, 'id' => $productId]);
+             }
+             if ($direction < 0) {
+                 $lowStock[$productId] = true;
+             }
+         }
+     }
+ 
+     private static function alertLowStock(array $productIds): void
+     {
+         if (empty($productIds)) {
+             return;
+         }
+         $threshold = max(0, (int) Shop::setting('shop_low_stock_threshold', '3'));
+         $recipient = self::adminEmail();
+         if ($recipient === null) {
+             return;
+         }
+ 
+         $siteDb = Database::site();
+         $low = [];
+         foreach (array_keys($productIds) as $productId) {
+             $statement = $siteDb->prepare(
+                 'SELECT p.id, p.title, p.stock_quantity,
+                     (SELECT MIN(v.stock_quantity) FROM product_variants v WHERE v.product_id = p.id AND v.stock_quantity IS NOT NULL) AS lowest_variant
+                  FROM products p WHERE p.id = :id AND p.track_inventory = 1
+                    AND (p.low_stock_alerted_at IS NULL OR p.low_stock_alerted_at < NOW() - INTERVAL 1 DAY) LIMIT 1'
+             );
+             $statement->execute(['id' => (int) $productId]);
+             $product = $statement->fetch();
+             if (!$product) {
+                 continue;
+             }
+             $levels = array_filter([$product['stock_quantity'], $product['lowest_variant']], static fn($value): bool => $value !== null);
+             if (empty($levels)) {
+                 continue;
+             }
+             $lowest = (int) min(array_map('intval', $levels));
+             if ($lowest > $threshold) {
+                 continue;
+             }
+             $siteDb->prepare('UPDATE products SET low_stock_alerted_at = NOW() WHERE id = :id')->execute(['id' => (int) $product['id']]);
+             $low[] = ['title' => (string) $product['title'], 'stock' => $lowest, 'id' => (int) $product['id']];
+         }
+ 
+         if (!empty($low)) {
+             self::mailSafely(function () use ($recipient, $low): void {
+                 $message = MailTemplates::lowStockEmail($low);
+                 Mailer::send($recipient, $message['subject'], $message['html']);
+             });
+         }
+     }
+ 
+     private static function notifyAdmin(array $order, array $items, bool $licensesMissing): void
+     {
+         $recipient = self::adminEmail();
+         if ($recipient === null || Shop::setting('shop_notify_new_orders', '1') !== '1') {
+             return;
+         }
+         self::mailSafely(function () use ($recipient, $order, $items, $licensesMissing): void {
+             $message = MailTemplates::adminNewOrderEmail($order, $items, $licensesMissing);
+             Mailer::send($recipient, $message['subject'], $message['html']);
+         });
+     }
+ 
+     public static function adminEmail(): ?string
+     {
+         foreach (['shop_notify_email', 'shop_contact_email', 'mail_from_email'] as $key) {
+             $email = trim(Shop::setting($key, ''));
+             if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
+                 return $email;
+             }
+         }
+ 
+         return null;
+     }
+ 
+     private static function assignInvoiceNumber(int $orderId): void
+     {
+         try {
+             $order = self::find($orderId);
+             if ($order === null || !empty($order['invoice_number'])) {
+                 return;
+             }
+             $siteDb = Database::site();
+             $siteDb->exec(
+                 "INSERT INTO site_settings (setting_key, setting_value) VALUES ('shop_invoice_counter', LAST_INSERT_ID(1))
+                  ON DUPLICATE KEY UPDATE setting_value = LAST_INSERT_ID(CAST(setting_value AS UNSIGNED) + 1)"
+             );
+             $number = (int) $siteDb->query('SELECT LAST_INSERT_ID()')->fetchColumn();
+             if ($number <= 0) {
+                 return;
+             }
+             $format = trim(Shop::setting('shop_invoice_format', ''));
+             if ($format === '' || !str_contains($format, '{number}')) {
+                 $format = 'INV-{year}-{number}';
+             }
+             $invoiceNumber = strtr($format, [
+                 '{year}' => date('Y'),
+                 '{month}' => date('m'),
+                 '{number}' => str_pad((string) $number, 5, '0', STR_PAD_LEFT),
+             ]);
+             Database::users()->prepare('UPDATE orders SET invoice_number = :number WHERE id = :id AND invoice_number IS NULL')
+                 ->execute(['number' => mb_substr($invoiceNumber, 0, 40), 'id' => $orderId]);
+         } catch (Throwable $exception) {
+             error_log('StocketBase: could not assign an invoice number to order ' . $orderId . ': ' . $exception->getMessage());
+         }
+     }
+ 
+     private static function nullable($value): ?string
+     {
+         $value = is_scalar($value) ? trim((string) $value) : '';
+ 
+         return $value !== '' ? $value : null;
+     }
+ 
+     private static function loadMailer(): bool
+     {
+         if (!is_file(__DIR__ . '/mailer.php') || !is_file(__DIR__ . '/mail-templates.php')) {
+             return false;
+         }
+         require_once __DIR__ . '/mailer.php';
+         require_once __DIR__ . '/mail-templates.php';
+ 
+         return class_exists('Mailer') && class_exists('MailTemplates');
+     }
+ 
+     private static function mailSafely(callable $send): void
+     {
+         if (!self::loadMailer()) {
+             return;
+         }
+         try {
+             $send();
+         } catch (Throwable $exception) {
+             error_log('StocketBase: email failed: ' . $exception->getMessage());
+         }
+     }
+ }
+ 
includes/payments/stripe-client.php Modified +24 -5
⋮ 139 unchanged lines ⋮
          return true;
      }
  
+     public function retrieveCheckoutSession(string $sessionId): ?array
+     {
+         if ($this->secretKey === '' || preg_match('/^cs_[A-Za-z0-9_]+$/', $sessionId) !== 1) {
+             return null;
+         }
+ 
+         [$status, $body] = $this->request('GET', '/checkout/sessions/' . rawurlencode($sessionId), []);
+ 
+         return $status >= 200 && $status < 300 && !empty($body['id']) ? $body : null;
+     }
+ 
      private function post(string $path, array $formData): array
      {
+         return $this->request('POST', $path, $formData);
+     }
+ 
+     private function request(string $method, string $path, array $formData): array
+     {
          $url = self::API_BASE . $path;
          $body = http_build_query($formData, '', '&', PHP_QUERY_RFC1738);
  
⋮ 3 unchanged lines ⋮
              return [0, []];
          }
  
-         $curl = curl_init($url);
-         curl_setopt_array($curl, [
-             CURLOPT_POST => true,
-             CURLOPT_POSTFIELDS => $body,
+         $curl = curl_init($method === 'GET' && $body !== '' ? $url . '?' . $body : $url);
+         $options = [
              CURLOPT_HTTPHEADER => [
                  'Authorization: Bearer ' . $this->secretKey,
                  'Content-Type: application/x-www-form-urlencoded',
⋮ 1 unchanged line ⋮
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_CONNECTTIMEOUT => 10,
              CURLOPT_TIMEOUT => 20,
-         ]);
+         ];
+         if ($method === 'POST') {
+             $options[CURLOPT_POST] = true;
+             $options[CURLOPT_POSTFIELDS] = $body;
+         }
+         curl_setopt_array($curl, $options);
          $response = curl_exec($curl);
          $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
          $curlError = curl_error($curl);
⋮ 14 unchanged lines ⋮
includes/shop.php Added +374 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/site-front.php';
+ require_once __DIR__ . '/currency.php';
+ require_once __DIR__ . '/countries.php';
+ require_once __DIR__ . '/language.php';
+ 
+ final class Shop
+ {
+     public const PAYMENT_METHODS = ['card', 'bank_transfer', 'cod', 'free'];
+     public const MAX_SHIPPING_METHODS = 20;
+ 
+     public static function setting(string $key, string $default = ''): string
+     {
+         $settings = SiteFront::settings();
+ 
+         return isset($settings[$key]) ? (string) $settings[$key] : $default;
+     }
+ 
+     public static function shippingMethods(): array
+     {
+         $decoded = json_decode(self::setting('shop_shipping_methods', '[]'), true);
+ 
+         return self::sanitizeShippingMethods(is_array($decoded) ? $decoded : []);
+     }
+ 
+     public static function sanitizeShippingMethods(array $rows): array
+     {
+         $methods = [];
+         $usedIds = [];
+         foreach ($rows as $row) {
+             if (!is_array($row) || count($methods) >= self::MAX_SHIPPING_METHODS) {
+                 continue;
+             }
+             $name = trim(strip_tags((string) ($row['name'] ?? '')));
+             if ($name === '') {
+                 continue;
+             }
+             $id = preg_replace('/[^a-z0-9]/', '', strtolower((string) ($row['id'] ?? '')));
+             if ($id === '' || isset($usedIds[$id])) {
+                 $id = substr(bin2hex(random_bytes(4)), 0, 8);
+             }
+             $usedIds[$id] = true;
+             $freeOver = $row['free_over_cents'] ?? null;
+             $methods[] = [
+                 'id' => $id,
+                 'name' => function_exists('mb_substr') ? mb_substr($name, 0, 120) : substr($name, 0, 120),
+                 'price_cents' => max(0, (int) ($row['price_cents'] ?? 0)),
+                 'free_over_cents' => $freeOver === null || $freeOver === '' ? null : max(0, (int) $freeOver),
+                 'countries' => Countries::parseList(is_array($row['countries'] ?? null) ? implode(' ', $row['countries']) : (string) ($row['countries'] ?? '')),
+                 'note' => function_exists('mb_substr') ? mb_substr(trim(strip_tags((string) ($row['note'] ?? ''))), 0, 160) : substr(trim(strip_tags((string) ($row['note'] ?? ''))), 0, 160),
+                 'cod' => !empty($row['cod']),
+             ];
+         }
+ 
+         return $methods;
+     }
+ 
+     public static function allowedCountries(): array
+     {
+         return Countries::parseList(self::setting('shop_countries', ''));
+     }
+ 
+     public static function countryOptions(): array
+     {
+         $allowed = self::allowedCountries();
+         $all = Countries::all();
+         if (empty($allowed)) {
+             return $all;
+         }
+ 
+         return array_intersect_key($all, array_flip($allowed));
+     }
+ 
+     public static function isCountryAllowed(string $code): bool
+     {
+         $code = strtoupper(trim($code));
+         if (!Countries::isValid($code)) {
+             return false;
+         }
+         $allowed = self::allowedCountries();
+ 
+         return empty($allowed) || in_array($code, $allowed, true);
+     }
+ 
+     public static function shippingOptions(string $country, int $goodsAfterDiscountCents): array
+     {
+         $country = strtoupper(trim($country));
+         $options = [];
+         foreach (self::shippingMethods() as $method) {
+             if (!empty($method['countries']) && ($country === '' || !in_array($country, $method['countries'], true))) {
+                 continue;
+             }
+             $cost = (int) $method['price_cents'];
+             if ($method['free_over_cents'] !== null && $goodsAfterDiscountCents >= (int) $method['free_over_cents']) {
+                 $cost = 0;
+             }
+             $method['cost_cents'] = $cost;
+             $options[] = $method;
+         }
+ 
+         return $options;
+     }
+ 
+     public static function taxEnabled(): bool
+     {
+         return self::setting('shop_tax_enabled', '0') === '1' && self::taxRateBasisPoints() > 0;
+     }
+ 
+     public static function taxRateBasisPoints(): int
+     {
+         $raw = str_replace(',', '.', trim(self::setting('shop_tax_rate', '0')));
+         if (!is_numeric($raw)) {
+             return 0;
+         }
+ 
+         return max(0, min(10000, (int) round(((float) $raw) * 100)));
+     }
+ 
+     public static function pricesIncludeTax(): bool
+     {
+         return self::setting('shop_prices_include_tax', '1') === '1';
+     }
+ 
+     public static function taxLabel(): string
+     {
+         $label = trim(self::setting('shop_tax_label', ''));
+ 
+         return $label !== '' ? $label : Language::get('checkout_tax_label', 'Tax');
+     }
+ 
+     public static function formatRate(int $basisPoints): string
+     {
+         $value = rtrim(rtrim(number_format($basisPoints / 100, 2, '.', ''), '0'), '.');
+ 
+         return $value . '%';
+     }
+ 
+     public static function computeTax(int $taxableCents, int $basisPoints, bool $inclusive): int
+     {
+         if ($taxableCents <= 0 || $basisPoints <= 0) {
+             return 0;
+         }
+         if ($inclusive) {
+             return $taxableCents - (int) round($taxableCents * 10000 / (10000 + $basisPoints));
+         }
+ 
+         return (int) round($taxableCents * $basisPoints / 10000);
+     }
+ 
+     public static function quote(array $items, ?array $discount, ?string $shippingMethodId, string $country, string $paymentMethod = ''): array
+     {
+         $subtotal = 0;
+         $requiresShipping = false;
+         foreach ($items as $item) {
+             $subtotal += (int) $item['total_cents'];
+             if (($item['product_kind'] ?? 'physical') === 'physical') {
+                 $requiresShipping = true;
+             }
+         }
+ 
+         $discountCents = 0;
+         if ($discount !== null) {
+             require_once __DIR__ . '/cart.php';
+             $discountCents = Cart::discountAmountCents($discount, $subtotal);
+         }
+         $goods = max(0, $subtotal - $discountCents);
+ 
+         $shippingCents = 0;
+         $shippingMethod = null;
+         $shippingOptions = [];
+         if ($requiresShipping) {
+             $shippingOptions = self::shippingOptions($country, $goods);
+             foreach ($shippingOptions as $option) {
+                 if ($option['id'] === (string) $shippingMethodId) {
+                     $shippingMethod = $option;
+                 }
+             }
+             if ($shippingMethod === null && count($shippingOptions) === 1) {
+                 $shippingMethod = $shippingOptions[0];
+             }
+             $shippingCents = $shippingMethod !== null ? (int) $shippingMethod['cost_cents'] : 0;
+         }
+ 
+         $codFee = 0;
+         if ($paymentMethod === 'cod') {
+             $codFee = max(0, (int) self::setting('shop_cod_fee_cents', '0'));
+         }
+ 
+         $rate = self::taxEnabled() ? self::taxRateBasisPoints() : 0;
+         $inclusive = self::pricesIncludeTax();
+         $taxable = $goods + (self::setting('shop_tax_shipping', '1') === '1' ? $shippingCents + $codFee : 0);
+         $taxCents = self::computeTax($taxable, $rate, $inclusive);
+         $total = $goods + $shippingCents + $codFee + ($inclusive ? 0 : $taxCents);
+ 
+         return [
+             'subtotal_cents' => $subtotal,
+             'discount_cents' => $discountCents,
+             'shipping_cents' => $shippingCents,
+             'cod_fee_cents' => $codFee,
+             'tax_cents' => $taxCents,
+             'tax_rate_bp' => $rate,
+             'prices_include_tax' => $inclusive,
+             'total_cents' => max(0, $total),
+             'requires_shipping' => $requiresShipping,
+             'shipping_method' => $shippingMethod,
+             'shipping_options' => $shippingOptions,
+         ];
+     }
+ 
+     public static function cardAvailable(): bool
+     {
+         return self::setting('shop_payment_card', '1') === '1'
+             && trim(self::setting('payment_stripe_secret_key', '')) !== '';
+     }
+ 
+     public static function paymentMethods(bool $requiresShipping, ?array $shippingMethod = null): array
+     {
+         $methods = [];
+         if (self::cardAvailable()) {
+             $methods['card'] = self::paymentLabel('card');
+         }
+         if (self::setting('shop_payment_bank', '0') === '1' && trim(self::setting('shop_bank_details', '')) !== '') {
+             $methods['bank_transfer'] = self::paymentLabel('bank_transfer');
+         }
+         if (self::setting('shop_payment_cod', '0') === '1' && $requiresShipping && ($shippingMethod === null || !empty($shippingMethod['cod']) || !self::anyShippingRestrictsCod())) {
+             $methods['cod'] = self::paymentLabel('cod');
+         }
+ 
+         return $methods;
+     }
+ 
+     private static function anyShippingRestrictsCod(): bool
+     {
+         foreach (self::shippingMethods() as $method) {
+             if (!empty($method['cod'])) {
+                 return true;
+             }
+         }
+ 
+         return false;
+     }
+ 
+     public static function paymentLabel(string $method): string
+     {
+         return match ($method) {
+             'card' => Language::get('payment_method_card', 'Card or online payment'),
+             'bank_transfer' => Language::get('payment_method_bank_transfer', 'Bank transfer'),
+             'cod' => Language::get('payment_method_cod', 'Cash on delivery'),
+             'free' => Language::get('payment_method_free', 'Free order'),
+             default => $method !== '' ? ucfirst(str_replace('_', ' ', $method)) : '',
+         };
+     }
+ 
+     public static function isOfflineMethod(string $method): bool
+     {
+         return in_array($method, ['bank_transfer', 'cod'], true);
+     }
+ 
+     public static function bankInstructions(array $order): string
+     {
+         $details = trim(self::setting('shop_bank_details', ''));
+         if ($details === '') {
+             return '';
+         }
+ 
+         return strtr($details, [
+             '{order}' => (string) ($order['order_number'] ?? ''),
+             '{total}' => Currency::format((int) ($order['total_cents'] ?? 0), (string) ($order['currency'] ?? Currency::DEFAULT_CODE)),
+         ]);
+     }
+ 
+     public static function bankPaymentDays(): int
+     {
+         return max(0, min(90, (int) self::setting('shop_bank_days', '7')));
+     }
+ 
+     public static function phoneFieldMode(): string
+     {
+         $mode = self::setting('shop_phone_field', 'optional');
+ 
+         return in_array($mode, ['hidden', 'optional', 'required'], true) ? $mode : 'optional';
+     }
+ 
+     public static function termsUrl(): string
+     {
+         return self::safeUrl(self::setting('shop_terms_url', ''));
+     }
+ 
+     public static function privacyUrl(): string
+     {
+         return self::safeUrl(self::setting('shop_privacy_url', ''));
+     }
+ 
+     public static function safeUrl(string $url): string
+     {
+         $url = trim($url);
+         if ($url === '') {
+             return '';
+         }
+         if (preg_match('#^https?://#i', $url) === 1) {
+             return filter_var($url, FILTER_VALIDATE_URL) !== false ? $url : '';
+         }
+         if (preg_match('#^[a-zA-Z0-9_\-./?=&%]+$#', $url) === 1 && !str_starts_with($url, '//')) {
+             return $url;
+         }
+ 
+         return '';
+     }
+ 
+     public static function companyLines(): array
+     {
+         $lines = [];
+         $name = trim(self::setting('shop_company_name', ''));
+         $lines[] = $name !== '' ? $name : self::setting('site_name', '');
+         foreach (preg_split('/\R/', self::setting('shop_company_address', '')) ?: [] as $line) {
+             if (trim($line) !== '') {
+                 $lines[] = trim($line);
+             }
+         }
+         $taxId = trim(self::setting('shop_tax_id', ''));
+         if ($taxId !== '') {
+             $lines[] = Language::get('receipt_tax_id', 'Tax ID') . ': ' . $taxId;
+         }
+         $email = trim(self::setting('shop_contact_email', ''));
+         if ($email !== '') {
+             $lines[] = $email;
+         }
+ 
+         return array_values(array_filter($lines, static fn(string $line): bool => $line !== ''));
+     }
+ 
+     public static function baseUrl(): string
+     {
+         return rtrim((string) Config::get('APP_URL', ''), '/') . Config::get('APP_BASE_PATH', '');
+     }
+ 
+     public static function orderUrl(array $order, bool $absolute = true): string
+     {
+         $token = (string) ($order['access_token'] ?? '');
+         $path = 'order-confirmation.php?order_id=' . (int) $order['id'] . ($token !== '' ? '&token=' . $token : '');
+ 
+         return $absolute ? self::baseUrl() . '/' . $path : $path;
+     }
+ 
+     public static function receiptUrl(array $order, bool $absolute = false): string
+     {
+         $token = (string) ($order['access_token'] ?? '');
+         $path = 'receipt.php?order_id=' . (int) $order['id'] . ($token !== '' ? '&token=' . $token : '');
+ 
+         return $absolute ? self::baseUrl() . '/' . $path : $path;
+     }
+ 
+     public static function addressLines(array $order, string $prefix): array
+     {
+         $country = (string) ($order[$prefix . '_country'] ?? '');
+         $lines = [
+             (string) ($order[$prefix . '_name'] ?? ''),
+             $prefix === 'billing' ? (string) ($order['billing_company'] ?? '') : '',
+             (string) ($order[$prefix . '_address_line1'] ?? ''),
+             (string) ($order[$prefix . '_address_line2'] ?? ''),
+             trim(((string) ($order[$prefix . '_postal_code'] ?? '')) . ' ' . ((string) ($order[$prefix . '_city'] ?? ''))),
+             (string) ($order[$prefix . '_region'] ?? ''),
+             $country !== '' ? Countries::name($country) : '',
+             $prefix === 'billing' && !empty($order['billing_tax_id']) ? Language::get('receipt_tax_id', 'Tax ID') . ': ' . $order['billing_tax_id'] : '',
+             $prefix === 'shipping' ? (string) ($order['shipping_phone'] ?? '') : '',
+         ];
+ 
+         return array_values(array_filter(array_map('trim', $lines), static fn(string $line): bool => $line !== ''));
+     }
+ }
+ 
includes/site-front.php Modified +26 -0
⋮ 64 unchanged lines ⋮
              'require_account_to_purchase' => '0',
              'download_link_expiry_days' => '30',
              'download_link_max_downloads' => '10',
+             'shop_shipping_methods' => '[]',
+             'shop_countries' => '',
+             'shop_default_country' => '',
+             'shop_tax_enabled' => '0',
+             'shop_tax_rate' => '0',
+             'shop_tax_label' => '',
+             'shop_prices_include_tax' => '1',
+             'shop_tax_shipping' => '1',
+             'shop_payment_card' => '1',
+             'shop_payment_bank' => '0',
+             'shop_bank_details' => '',
+             'shop_bank_days' => '7',
+             'shop_payment_cod' => '0',
+             'shop_cod_fee_cents' => '0',
+             'shop_phone_field' => 'optional',
+             'shop_terms_url' => '',
+             'shop_privacy_url' => '',
+             'shop_company_name' => '',
+             'shop_company_address' => '',
+             'shop_tax_id' => '',
+             'shop_contact_email' => '',
+             'shop_invoice_format' => 'INV-{year}-{number}',
+             'shop_receipt_note' => '',
+             'shop_notify_new_orders' => '1',
+             'shop_notify_email' => '',
+             'shop_low_stock_threshold' => '3',
              'contact_enabled' => '0',
              'contact_recipient_email' => '',
              'contact_provider' => 'php_mail',
⋮ 845 unchanged lines ⋮
order-confirmation.php Modified +90 -111
⋮ 8 unchanged lines ⋮
  require_once __DIR__ . '/includes/site-front.php';
  require_once __DIR__ . '/includes/cart.php';
  require_once __DIR__ . '/includes/currency.php';
+ require_once __DIR__ . '/includes/orders.php';
+ require_once __DIR__ . '/includes/order-view.php';
  
  UserAuth::boot();
  
  $settings = SiteFront::settings();
  $sessionId = trim((string) ($_GET['session_id'] ?? ''));
  $orderId = (int) ($_GET['order_id'] ?? 0);
+ $token = (string) ($_GET['token'] ?? '');
  
  $order = null;
- $orderItems = [];
+ $currentCustomer = UserAuth::user();
+ $sessionOwnsOrder = false;
  
  if ($orderId > 0) {
-     $usersDb = Database::users();
-     $statement = $usersDb->prepare('SELECT * FROM orders WHERE id = :id LIMIT 1');
-     $statement->execute(['id' => $orderId]);
-     $candidateOrder = $statement->fetch();
- 
-     $currentCustomer = UserAuth::user();
+     $candidateOrder = Orders::find($orderId);
      $sessionOwnsOrder = isset($_SESSION['checkout_order_ids']) && is_array($_SESSION['checkout_order_ids'])
-         && in_array($orderId, $_SESSION['checkout_order_ids'], true);
-     $accountOwnsOrder = $candidateOrder && $currentCustomer !== null
+         && in_array($orderId, array_map('intval', $_SESSION['checkout_order_ids']), true);
+     $accountOwnsOrder = $candidateOrder !== null && $currentCustomer !== null
          && $candidateOrder['user_account_id'] !== null
          && (int) $candidateOrder['user_account_id'] === (int) $currentCustomer['id'];
+     $tokenOwnsOrder = $token !== '' && Orders::findWithToken($orderId, $token) !== null;
  
-     if ($candidateOrder && ($sessionOwnsOrder || $accountOwnsOrder)) {
+     if ($candidateOrder !== null && ($sessionOwnsOrder || $accountOwnsOrder || $tokenOwnsOrder)) {
          $order = $candidateOrder;
-         $itemsStatement = $usersDb->prepare('SELECT * FROM order_items WHERE order_id = :id ORDER BY id ASC');
-         $itemsStatement->execute(['id' => $orderId]);
-         $orderItems = $itemsStatement->fetchAll();
      }
  }
  
- if ($sessionId !== '' || $order !== null) {
-     Cart::clear();
+ if ($order !== null && $order['status'] === 'pending' && $sessionId !== '' && ($order['payment_method'] ?? 'card') === 'card'
+     && (string) ($order['provider_checkout_id'] ?? '') === $sessionId && is_file(__DIR__ . '/includes/payments/stripe-client.php')) {
+     require_once __DIR__ . '/includes/payments/stripe-client.php';
+     $stripeSession = class_exists('StripeClient') ? (new StripeClient())->retrieveCheckoutSession($sessionId) : null;
+     $sessionOrderId = (int) ($stripeSession['metadata']['order_id'] ?? 0);
+     if ($stripeSession !== null && $sessionOrderId === (int) $order['id'] && ($stripeSession['payment_status'] ?? '') === 'paid'
+         && (int) ($stripeSession['amount_total'] ?? -1) === (int) $order['total_cents']
+         && strtoupper((string) ($stripeSession['currency'] ?? '')) === strtoupper((string) $order['currency'])) {
+         $paymentIntent = $stripeSession['payment_intent'] ?? null;
+         $customer = $stripeSession['customer'] ?? null;
+         Orders::markPaid((int) $order['id'], [
+             'provider' => 'stripe',
+             'checkout_id' => (string) $stripeSession['id'],
+             'payment_id' => is_array($paymentIntent) ? (string) ($paymentIntent['id'] ?? '') : (string) ($paymentIntent ?? ''),
+             'customer_id' => is_array($customer) ? (string) ($customer['id'] ?? '') : (string) ($customer ?? ''),
+         ], 'Payment confirmed when the customer returned from Stripe');
+         $order = Orders::find((int) $order['id']) ?? $order;
+     }
  }
  
- require_once __DIR__ . '/includes/digital-files.php';
+ if ($order !== null && $sessionOwnsOrder && $order['status'] !== 'failed') {
+     Cart::clear();
+ } elseif ($order === null && $sessionId !== '') {
+     Cart::clear();
+ }
  
- $orderHasDownloads = false;
- $orderDownloads = [];
+ $orderItems = $order !== null ? Orders::items((int) $order['id']) : [];
+ $viewerOwnsAccountOrder = $order !== null && $currentCustomer !== null && $order['user_account_id'] !== null
+     && (int) $order['user_account_id'] === (int) $currentCustomer['id'];
  if ($order !== null) {
-     $orderIsPaid = in_array($order['status'], DigitalFiles::PAID_ORDER_STATUSES, true);
-     $orderTokens = $orderIsPaid ? DigitalFiles::tokensForOrder((int) $order['id']) : [];
-     $viewer = UserAuth::user();
-     $viewerOwnsAccountOrder = $viewer !== null && $order['user_account_id'] !== null && (int) $order['user_account_id'] === (int) $viewer['id'];
- 
-     foreach (array_unique(array_map(static fn(array $item): int => (int) $item['product_id'], $orderItems)) as $orderProductId) {
-         $orderProductFiles = DigitalFiles::filesForProduct($orderProductId);
-         if (empty($orderProductFiles)) {
-             continue;
-         }
-         $orderHasDownloads = true;
- 
-         if (!$orderIsPaid) {
-             continue;
-         }
- 
-         $productToken = $viewerOwnsAccountOrder ? null : ($orderTokens[$orderProductId] ?? null);
-         if (!$viewerOwnsAccountOrder && $productToken === null) {
-             continue;
-         }
- 
-         foreach ($orderProductFiles as $orderProductFile) {
-             $orderDownloads[] = [
-                 'name' => DigitalFiles::displayName($orderProductFile),
-                 'size' => (int) $orderProductFile['size_bytes'],
-                 'url' => DigitalFiles::downloadUrl((int) $orderProductFile['id'], $productToken),
-             ];
-         }
-     }
+     $order = Orders::ensureAccessToken($order);
  }
  
- $pageTitle = Language::get('order_confirmation_title', 'Thank you') . ' - ' . $settings['site_name'];
+ $isPaid = $order !== null && in_array($order['status'], Orders::PAID_STATUSES, true);
+ $title = $order === null || $order['status'] !== 'failed'
+     ? Language::get('order_confirmation_title', 'Thank you')
+     : Language::get('order_failed_title', 'Payment not completed');
+ 
+ $pageTitle = $title . ' - ' . $settings['site_name'];
  $pageDescription = '';
+ $pageNoindex = true;
  
  require __DIR__ . '/includes/front-header.php';
  
  ?>
- <h1 class="article-title"><?= htmlspecialchars(Language::get('order_confirmation_title', 'Thank you')) ?></h1>
- 
- <?php if ($order !== null): ?>
-     <?php if ($order['status'] === 'pending'): ?>
-         <p><?= htmlspecialchars(Language::get('order_confirmation_processing', 'Your payment is still being processed. This page will show your final order status once confirmed — you will also receive a confirmation email.')) ?></p>
-     <?php else: ?>
-         <p><?= htmlspecialchars(Language::get('order_confirmation_success', 'Your order has been placed successfully.')) ?></p>
-     <?php endif; ?>
+ <div class="order-page">
+     <h1 class="article-title"><?= htmlspecialchars($title) ?></h1>
  
-     <div class="order-summary">
-         <p><strong><?= htmlspecialchars(Language::get('order_number_label', 'Order number')) ?>:</strong> <?= htmlspecialchars($order['order_number']) ?></p>
-         <p><strong><?= htmlspecialchars(Language::get('order_status_label', 'Status')) ?>:</strong> <span class="status-pill status-<?= htmlspecialchars($order['status']) ?>"><?= htmlspecialchars(Language::get('order_status_' . $order['status'], ucfirst($order['status']))) ?></span></p>
+     <?php if ($order !== null): ?>
+         <?php if ($isPaid): ?>
+             <p class="order-lead"><?= htmlspecialchars(Language::get('order_confirmation_success', 'Your order has been placed successfully.')) ?>
+                 <?php $confirmationEmail = Orders::customerEmail($order); ?>
+                 <?php if ($confirmationEmail !== null): ?>
+                     <?= htmlspecialchars(str_replace('{email}', $confirmationEmail, Language::get('order_confirmation_email_sent', 'We sent a confirmation to {email}.'))) ?>
+                 <?php endif; ?>
+             </p>
+         <?php endif; ?>
  
-         <table class="dash-table">
-             <thead>
-                 <tr>
-                     <th><?= htmlspecialchars(Language::get('cart_column_product', 'Product')) ?></th>
-                     <th><?= htmlspecialchars(Language::get('cart_column_quantity', 'Quantity')) ?></th>
-                     <th><?= htmlspecialchars(Language::get('cart_column_total', 'Total')) ?></th>
-                 </tr>
-             </thead>
-             <tbody>
-                 <?php foreach ($orderItems as $item): ?>
-                     <tr>
-                         <td><?= htmlspecialchars($item['product_title_snapshot']) ?><?= $item['variant_name_snapshot'] !== null ? ' — ' . htmlspecialchars($item['variant_name_snapshot']) : '' ?></td>
-                         <td><?= (int) $item['quantity'] ?></td>
-                         <td><?= htmlspecialchars(Currency::format((int) $item['total_cents'], $order['currency'])) ?></td>
-                     </tr>
-                 <?php endforeach; ?>
-             </tbody>
-         </table>
+         <?= OrderView::render($order, $orderItems, $viewerOwnsAccountOrder) ?>
  
-         <div class="cart-summary">
-             <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_subtotal', 'Subtotal')) ?></span><span><?= htmlspecialchars(Currency::format((int) $order['subtotal_cents'], $order['currency'])) ?></span></div>
-             <?php if ((int) $order['discount_cents'] > 0): ?>
-                 <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('cart_discount', 'Discount')) ?></span><span>-<?= htmlspecialchars(Currency::format((int) $order['discount_cents'], $order['currency'])) ?></span></div>
-             <?php endif; ?>
-             <?php if ((int) $order['shipping_cents'] > 0): ?>
-                 <div class="cart-summary-row"><span><?= htmlspecialchars(Language::get('order_shipping_label', 'Shipping')) ?></span><span><?= htmlspecialchars(Currency::format((int) $order['shipping_cents'], $order['currency'])) ?></span></div>
-             <?php endif; ?>
-             <div class="cart-summary-row cart-summary-total"><span><?= htmlspecialchars(Language::get('cart_total', 'Total')) ?></span><span><?= htmlspecialchars(Currency::format((int) $order['total_cents'], $order['currency'])) ?></span></div>
-         </div>
-     </div>
+         <?php if ($currentCustomer === null && UserAuth::registrationEnabled() && $order['status'] !== 'failed'): ?>
+             <div class="order-notice order-notice-plain">
+                 <p><?= htmlspecialchars(Language::get('order_create_account_hint', 'Create an account with the same email to keep all your orders, downloads and license keys in one place.')) ?></p>
+                 <a class="order-button" href="user-login.php?mode=register"><?= htmlspecialchars(Language::get('auth_register_button', 'Create account')) ?></a>
+             </div>
+         <?php elseif ($viewerOwnsAccountOrder): ?>
+             <p><a href="account.php?tab=orders&amp;order=<?= (int) $order['id'] ?>"><?= htmlspecialchars(Language::get('order_confirmation_view_account', 'View this order in your account')) ?></a></p>
+         <?php endif; ?>
  
-     <?php if ($orderHasDownloads): ?>
-         <h2><?= htmlspecialchars(Language::get('order_downloads_title', 'Your downloads')) ?></h2>
-         <?php if (!empty($orderDownloads)): ?>
-             <ul class="download-list">
-                 <?php foreach ($orderDownloads as $orderDownload): ?>
-                     <li>
-                         <a href="<?= htmlspecialchars($orderDownload['url']) ?>" rel="nofollow"><?= Icons::icon('download', 'icon icon-sm') ?><?= htmlspecialchars($orderDownload['name']) ?></a>
-                         <small><?= htmlspecialchars(DigitalFiles::formatSize($orderDownload['size'])) ?></small>
-                     </li>
-                 <?php endforeach; ?>
-             </ul>
-         <?php else: ?>
-             <p><?= htmlspecialchars(Language::get('order_downloads_pending', 'Your download links will appear here and be emailed to you as soon as the payment is confirmed. Refresh this page in a moment.')) ?></p>
+         <?php if ($order['status'] === 'failed'): ?>
+             <p><a class="order-button" href="cart.php"><?= htmlspecialchars(Language::get('order_back_to_cart', 'Back to cart')) ?></a></p>
          <?php endif; ?>
-     <?php endif; ?>
  
-     <?php if (UserAuth::check()): ?>
-         <p><a href="account.php?order=<?= (int) $order['id'] ?>"><?= htmlspecialchars(Language::get('order_confirmation_view_account', 'View this order in your account')) ?></a></p>
-     <?php endif; ?>
- <?php else: ?>
-     <p><?= htmlspecialchars(Language::get('order_confirmation_generic', 'Thank you! Your purchase is being confirmed — you will receive an email shortly.')) ?></p>
-     <?php if (UserAuth::check()): ?>
-         <p><a href="account.php"><?= htmlspecialchars(Language::get('order_confirmation_view_account', 'Go to your account')) ?></a></p>
+         <?php if (!$isPaid && $order['status'] === 'pending' && ($order['payment_method'] ?? 'card') === 'card' && $sessionId !== ''): ?>
+             <script>
+                 (function () {
+                     var key = 'sb_order_reload_<?= (int) $order['id'] ?>';
+                     var count = 0;
+                     try { count = parseInt(sessionStorage.getItem(key) || '0', 10); } catch (e) {}
+                     if (count >= 10) {
+                         return;
+                     }
+                     setTimeout(function () {
+                         try { sessionStorage.setItem(key, String(count + 1)); } catch (e) {}
+                         window.location.reload();
+                     }, 5000);
+                 })();
+             </script>
+         <?php endif; ?>
+         <?= OrderView::copyScript() ?>
+     <?php else: ?>
+         <p><?= htmlspecialchars(Language::get('order_confirmation_generic', 'Thank you! Your purchase is being confirmed — you will receive an email shortly.')) ?></p>
+         <?php if (UserAuth::check()): ?>
+             <p><a href="account.php?tab=orders"><?= htmlspecialchars(Language::get('order_confirmation_view_account', 'Go to your account')) ?></a></p>
+         <?php endif; ?>
      <?php endif; ?>
- <?php endif; ?>
  
- <p><a href="index.php"><?= htmlspecialchars(Language::get('order_confirmation_continue_shopping', 'Continue shopping')) ?></a></p>
+     <p><a href="index.php"><?= htmlspecialchars(Language::get('order_confirmation_continue_shopping', 'Continue shopping')) ?></a></p>
+ </div>
  
  <?php require __DIR__ . '/includes/front-footer.php'; ?>
  
receipt.php Added +179 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ require_once __DIR__ . '/includes/config.php';
+ require_once __DIR__ . '/includes/database.php';
+ require_once __DIR__ . '/includes/user-auth.php';
+ require_once __DIR__ . '/includes/language.php';
+ require_once __DIR__ . '/includes/site-front.php';
+ require_once __DIR__ . '/includes/currency.php';
+ require_once __DIR__ . '/includes/orders.php';
+ require_once __DIR__ . '/includes/order-view.php';
+ require_once __DIR__ . '/includes/asset.php';
+ 
+ UserAuth::boot();
+ 
+ $orderId = (int) ($_GET['order_id'] ?? 0);
+ $token = (string) ($_GET['token'] ?? '');
+ $customer = UserAuth::user();
+ $order = Orders::find($orderId);
+ 
+ $allowed = $order !== null && (
+     ($token !== '' && Orders::findWithToken($orderId, $token) !== null)
+     || ($customer !== null && $order['user_account_id'] !== null && (int) $order['user_account_id'] === (int) $customer['id'])
+     || (isset($_SESSION['checkout_order_ids']) && is_array($_SESSION['checkout_order_ids']) && in_array($orderId, array_map('intval', $_SESSION['checkout_order_ids']), true))
+ );
+ 
+ if (!$allowed || !in_array($order['status'], array_merge(Orders::PAID_STATUSES, ['refunded']), true)) {
+     http_response_code(404);
+     header('X-Robots-Tag: noindex, nofollow');
+     echo htmlspecialchars(Language::get('receipt_not_found', 'This receipt is not available.'));
+     exit;
+ }
+ 
+ $items = Orders::items($orderId);
+ $settings = SiteFront::settings();
+ $currency = (string) $order['currency'];
+ $e = static fn($value): string => htmlspecialchars((string) $value, ENT_QUOTES);
+ $buyer = Shop::addressLines($order, 'billing');
+ if (empty($buyer)) {
+     $buyer = Shop::addressLines($order, 'shipping');
+ }
+ $buyerEmail = Orders::customerEmail($order);
+ $documentNumber = (string) ($order['invoice_number'] ?: $order['order_number']);
+ $paidAt = !empty($order['paid_at']) ? OrderView::date((string) $order['paid_at']) : OrderView::date((string) $order['created_at']);
+ $taxRate = (int) ($order['tax_rate_bp'] ?? 0);
+ $netTotal = (int) $order['total_cents'] - (int) $order['tax_cents'];
+ $footerNote = trim(Shop::setting('shop_receipt_note', ''));
+ 
+ header('X-Robots-Tag: noindex, nofollow');
+ ?>
+ <!DOCTYPE html>
+ <html lang="<?= $e(Languages::htmlLang()) ?>">
+ <head>
+     <meta charset="utf-8">
+     <meta name="viewport" content="width=device-width, initial-scale=1">
+     <meta name="robots" content="noindex, nofollow">
+     <title><?= $e(Language::get('receipt_title', 'Receipt')) ?> <?= $e($documentNumber) ?> - <?= $e($settings['site_name']) ?></title>
+     <?= Asset::favicon() ?>
+     <style>
+         :root { color-scheme: light; }
+         * { box-sizing: border-box; }
+         body { margin: 0; padding: 32px 16px; background: #f1f5f9; color: #0f172a; font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; }
+         .receipt { max-width: 780px; margin: 0 auto; padding: 40px; background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; }
+         .receipt-top { display: flex; justify-content: space-between; gap: 24px; flex-wrap: wrap; margin-bottom: 32px; }
+         .receipt-top h1 { margin: 0 0 6px; font-size: 24px; }
+         .receipt-meta { margin: 0; color: #475569; }
+         .receipt-meta strong { color: #0f172a; }
+         .receipt-parties { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 28px; }
+         .receipt-parties h2 { margin: 0 0 6px; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: #64748b; }
+         .receipt-parties p { margin: 0; }
+         table { width: 100%; border-collapse: collapse; }
+         th { padding: 10px 8px; border-bottom: 2px solid #0f172a; font-size: 12px; text-align: left; text-transform: uppercase; letter-spacing: .04em; }
+         td { padding: 10px 8px; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
+         td small { display: block; color: #64748b; }
+         .num { text-align: right; white-space: nowrap; }
+         .receipt-totals { width: 100%; max-width: 340px; margin: 18px 0 0 auto; }
+         .receipt-totals div { display: flex; justify-content: space-between; gap: 16px; padding: 5px 8px; }
+         .receipt-totals .grand { margin-top: 6px; padding-top: 10px; border-top: 2px solid #0f172a; font-size: 16px; font-weight: 700; }
+         .receipt-foot { margin-top: 32px; padding-top: 16px; border-top: 1px solid #e2e8f0; color: #64748b; font-size: 12.5px; }
+         .receipt-refunded { display: inline-block; margin-top: 8px; padding: 4px 10px; border-radius: 999px; background: #fef2f2; color: #b91c1c; font-weight: 600; font-size: 12px; }
+         .receipt-actions { max-width: 780px; margin: 0 auto 16px; display: flex; justify-content: flex-end; gap: 8px; }
+         .receipt-actions button, .receipt-actions a { padding: 9px 16px; border: 1px solid #cbd5e1; border-radius: 8px; background: #fff; color: #0f172a; font: inherit; font-weight: 600; text-decoration: none; cursor: pointer; }
+         .receipt-actions button { background: #0f172a; border-color: #0f172a; color: #fff; }
+         @media (max-width: 640px) { .receipt { padding: 24px; } .receipt-parties { grid-template-columns: 1fr; } }
+         @media print { body { padding: 0; background: #fff; } .receipt { border: 0; padding: 0; } .receipt-actions { display: none; } }
+     </style>
+ </head>
+ <body>
+     <div class="receipt-actions">
+         <a href="index.php"><?= $e(Language::get('receipt_back', 'Back to the store')) ?></a>
+         <button type="button" onclick="window.print()"><?= $e(Language::get('receipt_print', 'Print or save as PDF')) ?></button>
+     </div>
+     <main class="receipt">
+         <div class="receipt-top">
+             <div>
+                 <h1><?= $e(Language::get('receipt_title', 'Receipt')) ?></h1>
+                 <p class="receipt-meta"><?= $e(Language::get('receipt_number', 'Number')) ?>: <strong><?= $e($documentNumber) ?></strong></p>
+                 <p class="receipt-meta"><?= $e(Language::get('order_number_label', 'Order number')) ?>: <?= $e($order['order_number']) ?></p>
+                 <?php if ($order['status'] === 'refunded'): ?>
+                     <span class="receipt-refunded"><?= $e(OrderView::statusLabel('refunded')) ?></span>
+                 <?php endif; ?>
+             </div>
+             <div style="text-align:right;">
+                 <p class="receipt-meta"><?= $e(Language::get('receipt_order_date', 'Order date')) ?>: <strong><?= $e(OrderView::date((string) $order['created_at'])) ?></strong></p>
+                 <p class="receipt-meta"><?= $e(Language::get('receipt_paid_date', 'Paid on')) ?>: <strong><?= $e($paidAt) ?></strong></p>
+                 <p class="receipt-meta"><?= $e(Language::get('order_payment_label', 'Payment')) ?>: <?= $e(Shop::paymentLabel((string) ($order['payment_method'] ?: 'card'))) ?></p>
+             </div>
+         </div>
+ 
+         <div class="receipt-parties">
+             <div>
+                 <h2><?= $e(Language::get('receipt_seller', 'Seller')) ?></h2>
+                 <p><?= implode('<br>', array_map($e, Shop::companyLines())) ?></p>
+             </div>
+             <div>
+                 <h2><?= $e(Language::get('receipt_buyer', 'Buyer')) ?></h2>
+                 <p><?= implode('<br>', array_map($e, $buyer)) ?><?= $buyerEmail !== null ? (empty($buyer) ? '' : '<br>') . $e($buyerEmail) : '' ?></p>
+             </div>
+         </div>
+ 
+         <table>
+             <thead>
+                 <tr>
+                     <th><?= $e(Language::get('cart_column_product', 'Product')) ?></th>
+                     <th class="num"><?= $e(Language::get('receipt_unit_price', 'Unit price')) ?></th>
+                     <th class="num"><?= $e(Language::get('email_column_qty', 'Qty')) ?></th>
+                     <th class="num"><?= $e(Language::get('cart_column_total', 'Total')) ?></th>
+                 </tr>
+             </thead>
+             <tbody>
+                 <?php foreach ($items as $item): ?>
+                     <tr>
+                         <td><?= $e($item['product_title_snapshot']) ?><?php if ($item['variant_name_snapshot'] !== null): ?><small><?= $e($item['variant_name_snapshot']) ?></small><?php endif; ?></td>
+                         <td class="num"><?= $e(Currency::format((int) $item['unit_price_cents'], $currency)) ?></td>
+                         <td class="num"><?= (int) $item['quantity'] ?></td>
+                         <td class="num"><?= $e(Currency::format((int) $item['total_cents'], $currency)) ?></td>
+                     </tr>
+                 <?php endforeach; ?>
+                 <?php if ((int) $order['shipping_cents'] > 0): ?>
+                     <tr>
+                         <td><?= $e(Language::get('order_shipping_label', 'Shipping')) ?><?php if (!empty($order['shipping_method'])): ?><small><?= $e($order['shipping_method']) ?></small><?php endif; ?></td>
+                         <td class="num"><?= $e(Currency::format((int) $order['shipping_cents'], $currency)) ?></td>
+                         <td class="num">1</td>
+                         <td class="num"><?= $e(Currency::format((int) $order['shipping_cents'], $currency)) ?></td>
+                     </tr>
+                 <?php endif; ?>
+                 <?php if ((int) ($order['cod_fee_cents'] ?? 0) > 0): ?>
+                     <tr>
+                         <td><?= $e(Language::get('order_cod_fee_label', 'Cash on delivery fee')) ?></td>
+                         <td class="num"><?= $e(Currency::format((int) $order['cod_fee_cents'], $currency)) ?></td>
+                         <td class="num">1</td>
+                         <td class="num"><?= $e(Currency::format((int) $order['cod_fee_cents'], $currency)) ?></td>
+                     </tr>
+                 <?php endif; ?>
+             </tbody>
+         </table>
+ 
+         <div class="receipt-totals">
+             <?php if ((int) $order['discount_cents'] > 0): ?>
+                 <div><span><?= $e(Language::get('cart_discount', 'Discount')) ?><?= !empty($order['discount_code']) ? ' (' . $e($order['discount_code']) . ')' : '' ?></span><span>-<?= $e(Currency::format((int) $order['discount_cents'], $currency)) ?></span></div>
+             <?php endif; ?>
+             <?php if ((int) $order['tax_cents'] > 0): ?>
+                 <div><span><?= $e(Language::get('receipt_net', 'Net amount')) ?></span><span><?= $e(Currency::format($netTotal, $currency)) ?></span></div>
+                 <div><span><?= $e(Shop::taxLabel()) ?><?= $taxRate > 0 ? ' ' . $e(Shop::formatRate($taxRate)) : '' ?></span><span><?= $e(Currency::format((int) $order['tax_cents'], $currency)) ?></span></div>
+             <?php endif; ?>
+             <div class="grand"><span><?= $e(Language::get('cart_total', 'Total')) ?></span><span><?= $e(Currency::format((int) $order['total_cents'], $currency)) ?></span></div>
+         </div>
+ 
+         <div class="receipt-foot">
+             <?php if ($footerNote !== ''): ?>
+                 <p><?= nl2br($e($footerNote)) ?></p>
+             <?php endif; ?>
+             <p><?= $e($settings['site_name']) ?> · <?= $e(Shop::baseUrl()) ?></p>
+         </div>
+     </main>
+ </body>
+ </html>
+ 
settings.php Modified

Not shown (binary file or too large to diff).

sql/schema_site.sql Modified +3 -0
⋮ 68 unchanged lines ⋮
      weight_grams INT NULL,
      stripe_price_id VARCHAR(190) NULL,
      polar_product_id VARCHAR(190) NULL,
+     license_mode VARCHAR(10) NOT NULL DEFAULT 'none',
+     license_pattern VARCHAR(80) NULL,
+     low_stock_alerted_at DATETIME NULL,
      sales_count INT UNSIGNED NOT NULL DEFAULT 0,
      status ENUM('draft','pending_review','scheduled','published','rejected','archived') NOT NULL DEFAULT 'draft',
      rejection_reason VARCHAR(500) NULL,
⋮ 146 unchanged lines ⋮
sql/schema_users.sql Modified +68 -0
⋮ 6 unchanged lines ⋮
      email VARCHAR(190) NOT NULL,
      password_hash VARCHAR(255) NOT NULL,
      display_name VARCHAR(120) NULL,
+     phone VARCHAR(40) NULL,
+     marketing_opt_in TINYINT(1) NOT NULL DEFAULT 0,
      avatar_path VARCHAR(255) NULL,
      email_verified_at DATETIME NULL,
      status ENUM('active','suspended','deleted') NOT NULL DEFAULT 'active',
⋮ 53 unchanged lines ⋮
      guest_email VARCHAR(190) NULL,
      status ENUM('pending','paid','processing','fulfilled','shipped','completed','canceled','refunded','failed') NOT NULL DEFAULT 'pending',
      provider VARCHAR(60) NULL,
+     payment_method VARCHAR(30) NULL,
      provider_checkout_id VARCHAR(190) NULL,
      provider_payment_id VARCHAR(190) NULL,
      provider_customer_id VARCHAR(190) NULL,
⋮ 1 unchanged line ⋮
      subtotal_cents INT UNSIGNED NOT NULL DEFAULT 0,
      discount_cents INT UNSIGNED NOT NULL DEFAULT 0,
      shipping_cents INT UNSIGNED NOT NULL DEFAULT 0,
+     shipping_method VARCHAR(160) NULL,
+     cod_fee_cents INT UNSIGNED NOT NULL DEFAULT 0,
      tax_cents INT UNSIGNED NOT NULL DEFAULT 0,
+     prices_include_tax TINYINT(1) NOT NULL DEFAULT 0,
+     tax_rate_bp INT UNSIGNED NOT NULL DEFAULT 0,
      total_cents INT UNSIGNED NOT NULL DEFAULT 0,
      discount_code VARCHAR(60) NULL,
      shipping_name VARCHAR(190) NULL,
⋮ 3 unchanged lines ⋮
      shipping_region VARCHAR(120) NULL,
      shipping_postal_code VARCHAR(30) NULL,
      shipping_country CHAR(2) NULL,
+     shipping_phone VARCHAR(40) NULL,
      billing_same_as_shipping TINYINT(1) NOT NULL DEFAULT 1,
      billing_name VARCHAR(190) NULL,
+     billing_company VARCHAR(190) NULL,
+     billing_tax_id VARCHAR(60) NULL,
      billing_address_line1 VARCHAR(255) NULL,
      billing_address_line2 VARCHAR(255) NULL,
      billing_city VARCHAR(120) NULL,
⋮ 5 unchanged lines ⋮
      tracking_url VARCHAR(255) NULL,
      fulfilled_at DATETIME NULL,
      shipped_at DATETIME NULL,
+     access_token CHAR(64) NULL,
+     invoice_number VARCHAR(40) NULL,
+     paid_at DATETIME NULL,
+     canceled_at DATETIME NULL,
+     stock_reserved TINYINT(1) NOT NULL DEFAULT 0,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      UNIQUE KEY uq_order_number (order_number),
+     UNIQUE KEY uq_order_access_token (access_token),
      KEY idx_order_account (user_account_id),
      KEY idx_order_status (status),
      KEY idx_order_provider_checkout (provider, provider_checkout_id),
⋮ 72 unchanged lines ⋮
      KEY idx_download_order (order_id),
      KEY idx_download_product (product_id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ 
+ CREATE TABLE IF NOT EXISTS user_addresses (
+     id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+     user_account_id INT UNSIGNED NOT NULL,
+     label VARCHAR(60) NULL,
+     full_name VARCHAR(190) NOT NULL,
+     company VARCHAR(190) NULL,
+     tax_id VARCHAR(60) NULL,
+     address_line1 VARCHAR(255) NOT NULL,
+     address_line2 VARCHAR(255) NULL,
+     city VARCHAR(120) NOT NULL,
+     region VARCHAR(120) NULL,
+     postal_code VARCHAR(30) NOT NULL,
+     country CHAR(2) NOT NULL,
+     phone VARCHAR(40) NULL,
+     is_default_shipping TINYINT(1) NOT NULL DEFAULT 0,
+     is_default_billing TINYINT(1) NOT NULL DEFAULT 0,
+     created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+     updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+     KEY idx_address_account (user_account_id),
+     CONSTRAINT fk_address_account FOREIGN KEY (user_account_id) REFERENCES user_accounts(id) ON DELETE CASCADE
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ 
+ CREATE TABLE IF NOT EXISTS account_tokens (
+     id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+     user_account_id INT UNSIGNED NOT NULL,
+     purpose VARCHAR(20) NOT NULL,
+     token_hash CHAR(64) NOT NULL,
+     expires_at DATETIME NOT NULL,
+     used_at DATETIME NULL,
+     created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+     UNIQUE KEY uq_account_token_hash (token_hash),
+     KEY idx_account_token_user (user_account_id, purpose),
+     CONSTRAINT fk_account_token_account FOREIGN KEY (user_account_id) REFERENCES user_accounts(id) ON DELETE CASCADE
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ 
+ CREATE TABLE IF NOT EXISTS license_keys (
+     id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+     product_id INT UNSIGNED NOT NULL,
+     license_key VARCHAR(255) NOT NULL,
+     source ENUM('pool','generated') NOT NULL DEFAULT 'pool',
+     order_id INT UNSIGNED NULL,
+     order_item_id INT UNSIGNED NULL,
+     user_account_id INT UNSIGNED NULL,
+     assigned_at DATETIME NULL,
+     revoked_at DATETIME NULL,
+     created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+     UNIQUE KEY uq_license_product_key (product_id, license_key),
+     KEY idx_license_free (product_id, order_id),
+     KEY idx_license_order (order_id),
+     KEY idx_license_account (user_account_id)
+             ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  
  SET FOREIGN_KEY_CHECKS = 1;
  
translations/language.php Modified +167 -1
⋮ 123 unchanged lines ⋮
      'checkout_postal_code' => 'Postal code',
      'checkout_country' => 'Country (2-letter code)',
      'checkout_note_label' => 'Order note (optional)',
-     'checkout_tax_note' => 'Tax is not calculated in this version.',
+     'checkout_tax_note' => 'Tax is shown in the summary.',
      'checkout_place_order' => 'Place order',
      'checkout_pay_button' => 'Continue to payment',
      'product_subscribe_polar_button' => 'Subscribe via Polar',
⋮ 198 unchanged lines ⋮
      'product_rating_aria' => 'Average rating {rating} out of 5',
      'antibot_image_label' => 'Security code',
      'checkout_discount_name' => 'Discount',
+     'account_add_address' => 'Add an address',
+     'account_address_default_set' => 'Default address changed.',
+     'account_address_delete_confirm' => 'Delete this address?',
+     'account_address_deleted' => 'Address deleted.',
+     'account_address_incomplete' => 'Please fill in the name, address, postal code, city and country.',
+     'account_address_label' => 'Name for this address (optional, e.g. Home or Office)',
+     'account_address_limit' => 'You can save up to 20 addresses.',
+     'account_address_saved' => 'Address saved.',
+     'account_cancel' => 'Cancel',
+     'account_change_email' => 'Change email',
+     'account_change_password' => 'Change password',
+     'account_current_password_short' => 'Current password',
+     'account_default_billing' => 'Default for billing',
+     'account_default_shipping' => 'Default for delivery',
+     'account_delete' => 'Delete',
+     'account_delete_button' => 'Delete my account',
+     'account_delete_check' => 'I understand that this cannot be undone',
+     'account_delete_confirm' => 'Delete your account for good? This cannot be undone.',
+     'account_delete_confirm_missing' => 'Please tick the box to confirm.',
+     'account_delete_hint' => 'We remove your personal details and log you out. Orders stay in our records because the law requires it, but they are no longer linked to a login.',
+     'account_delete_title' => 'Delete account',
+     'account_deleted' => 'Your account was deleted.',
+     'account_details' => 'Your details',
+     'account_edit' => 'Edit',
+     'account_edit_address' => 'Edit address',
+     'account_email_changed' => 'Email changed. We sent a confirmation link to the new address.',
+     'account_email_current' => 'Current email:',
+     'account_email_same' => 'That is already your email address.',
+     'account_email_title' => 'Email address',
+     'account_email_verified' => 'confirmed',
+     'account_export_button' => 'Download my data',
+     'account_export_hint' => 'Get a file with your account details, addresses, orders and license keys.',
+     'account_export_title' => 'Download your data',
+     'account_file_updated' => 'updated {date}',
+     'account_hello' => 'Hi, {name}',
+     'account_make_default_billing' => 'Use for billing',
+     'account_make_default_shipping' => 'Use for delivery',
+     'account_marketing' => 'Send me news and offers by email',
+     'account_new_email' => 'New email address',
+     'account_new_password_short' => 'New password',
+     'account_no_downloads' => 'Files you buy will show up here.',
+     'account_no_licenses' => 'License keys for software you buy will show up here.',
+     'account_password_title' => 'Password',
+     'account_password_updated' => 'Password changed. Other devices were logged out.',
+     'account_recent_orders' => 'Recent orders',
+     'account_subscription_until' => 'until {date}',
+     'account_tab_addresses' => 'Addresses',
+     'account_tab_downloads' => 'Downloads',
+     'account_tab_licenses' => 'License keys',
+     'account_tab_orders' => 'Orders',
+     'account_tab_overview' => 'Overview',
+     'account_tab_privacy' => 'Privacy',
+     'account_tab_profile' => 'Profile',
+     'account_title' => 'My account',
+     'account_verification_sent' => 'We sent you a new confirmation link.',
+     'account_verification_wait' => 'Please wait a minute before asking for another link.',
+     'account_verify_notice' => 'Please confirm your email address ({email}). After that, orders you placed as a guest with this email will show up here.',
+     'account_verify_resend' => 'Send the link again',
+     'auth_back_to_login' => 'Back to log in',
+     'auth_forgot_button' => 'Send the link',
+     'auth_forgot_intro' => 'Enter the email you use for your account. We will send you a link to set a new password.',
+     'auth_forgot_link' => 'Forgot your password?',
+     'auth_reset_button' => 'Save the new password',
+     'auth_reset_done' => 'Your password was changed. Log in with the new password.',
+     'auth_reset_invalid' => 'This reset link has expired or was already used. Ask for a new one below.',
+     'auth_reset_sent' => 'If an account with this email exists, we sent a link to set a new password. Check your inbox and spam folder.',
+     'auth_verified' => 'Email confirmed. Thank you!',
+     'auth_verified_claimed' => 'Email confirmed. We added {count} earlier orders to your account.',
+     'auth_verified_login' => 'Email confirmed. You can log in now.',
+     'auth_verify_invalid' => 'This confirmation link has expired or was already used. Log in and ask for a new one.',
+     'cart_delivery_note' => 'Delivery options and costs are shown at checkout.',
+     'cart_free_shipping_missing' => 'Add {amount} more for free delivery.',
+     'cart_free_shipping_reached' => 'You get free delivery.',
+     'cart_tax_added_note' => '{tax} and delivery are added at checkout.',
+     'cart_tax_included' => 'included',
+     'cart_tax_included_note' => 'Prices include {tax}. Delivery is added at checkout.',
+     'cart_total_before_delivery' => 'Total without delivery',
+     'checkout_accept_terms' => 'I accept the {terms} and the {privacy}.',
+     'checkout_back_to_cart' => 'Back to cart',
+     'checkout_choose_country' => 'Choose a country',
+     'checkout_company' => 'Company name',
+     'checkout_contact_title' => 'Contact',
+     'checkout_country_label' => 'Country',
+     'checkout_delivery_included' => 'Delivery is included in the price.',
+     'checkout_delivery_title' => 'Delivery',
+     'checkout_email_hint' => 'We send the order confirmation and any download links here.',
+     'checkout_error_country' => 'We do not ship to this country.',
+     'checkout_error_fields' => 'Please check the highlighted fields.',
+     'checkout_error_no_shipping' => 'There is no delivery option for this country.',
+     'checkout_error_payment_method' => 'Please choose how you want to pay.',
+     'checkout_error_required' => 'This field is required.',
+     'checkout_error_shipping_method' => 'Please choose how you want it delivered.',
+     'checkout_error_stock' => 'Some products are no longer available in the quantity you chose:',
+     'checkout_error_terms' => 'Please accept the terms to place your order.',
+     'checkout_free_over' => 'Free from {amount}',
+     'checkout_have_account' => 'Have an account? Log in',
+     'checkout_logged_in_as' => 'Ordering as',
+     'checkout_payment_title' => 'Payment',
+     'checkout_phone' => 'Phone number',
+     'checkout_phone_optional' => 'Phone number (optional, for the courier)',
+     'checkout_privacy_link' => 'privacy policy',
+     'checkout_save_address' => 'Save this address in my account',
+     'checkout_saved_address' => 'Use a saved address',
+     'checkout_secure_note' => 'Your details are sent securely.',
+     'checkout_shipping_free' => 'Free',
+     'checkout_summary_title' => 'Your order',
+     'checkout_tax_id' => 'Tax ID (VAT number)',
+     'checkout_tax_label' => 'Tax',
+     'checkout_terms_link' => 'terms of sale',
+     'checkout_wants_invoice' => 'I need an invoice for a company',
+     'email_bank_days' => 'Please pay within {days} days, otherwise the order may be canceled.',
+     'email_bank_title' => 'How to pay',
+     'email_bank_title_reference' => 'Please put this in the transfer title:',
+     'email_licenses_title' => 'Your license keys',
+     'email_placed_bank_intro' => 'We have received your order. It will be processed as soon as your transfer arrives.',
+     'email_placed_cod_intro' => 'We have received your order. You will pay when it is delivered.',
+     'email_placed_heading' => 'Thanks for your order!',
+     'email_placed_subject' => 'Order received — {site} #{order}',
+     'email_reset_button' => 'Set a new password',
+     'email_reset_heading' => 'Reset your password',
+     'email_reset_ignore' => 'If you did not ask for this, you can ignore this email. Your password stays the same.',
+     'email_reset_intro' => 'Someone asked to reset the password for your account. If it was you, click the button below. The link works for one hour.',
+     'email_reset_subject' => 'Reset your password — {site}',
+     'email_verify_button' => 'Confirm email',
+     'email_verify_heading' => 'Confirm your email',
+     'email_verify_intro' => 'Please confirm this is your email address. After that, orders you placed as a guest with this email show up in your account.',
+     'email_verify_subject' => 'Confirm your email — {site}',
+     'email_view_order' => 'View your order',
+     'order_back_to_cart' => 'Back to cart',
+     'order_bank_amount' => 'Amount',
+     'order_bank_intro' => 'Send the amount below to this account. We will process your order as soon as the money arrives.',
+     'order_bank_reference' => 'Transfer title',
+     'order_bank_title' => 'Waiting for your bank transfer',
+     'order_cod_fee_label' => 'Cash on delivery fee',
+     'order_cod_note' => 'You will pay when the parcel is delivered.',
+     'order_confirmation_email_sent' => 'We sent a confirmation to {email}.',
+     'order_create_account_hint' => 'Create an account with the same email to keep all your orders, downloads and license keys in one place.',
+     'order_downloads_left' => '{count} downloads left',
+     'order_downloads_unlimited' => 'No limit while you are logged in.',
+     'order_downloads_until' => 'link works until {date}',
+     'order_failed_note' => 'The payment did not go through, so the order was not placed. You can try again from your cart.',
+     'order_failed_title' => 'Payment not completed',
+     'order_history_title' => 'What happened',
+     'order_licenses_title' => 'License keys',
+     'order_payment_label' => 'Payment',
+     'order_receipt_button' => 'Receipt',
+     'payment_method_bank_note' => 'We send the bank details after you place the order. We ship once the money arrives.',
+     'payment_method_bank_transfer' => 'Bank transfer',
+     'payment_method_card' => 'Card or online payment',
+     'payment_method_card_note' => 'Pay securely online. You will be redirected to the payment page.',
+     'payment_method_cod' => 'Cash on delivery',
+     'payment_method_cod_fee_note' => 'Pay the courier when it arrives. Extra fee: {amount}.',
+     'payment_method_cod_note' => 'Pay the courier when it arrives.',
+     'payment_method_free' => 'Free order',
+     'receipt_back' => 'Back to the store',
+     'receipt_buyer' => 'Buyer',
+     'receipt_net' => 'Net amount',
+     'receipt_not_found' => 'This receipt is not available.',
+     'receipt_number' => 'Number',
+     'receipt_order_date' => 'Order date',
+     'receipt_paid_date' => 'Paid on',
+     'receipt_print' => 'Print or save as PDF',
+     'receipt_seller' => 'Seller',
+     'receipt_tax_id' => 'Tax ID',
+     'receipt_title' => 'Receipt',
+     'receipt_unit_price' => 'Unit price',
  ];
  
user-login.php Modified +124 -5
⋮ 36 unchanged lines ⋮
      exit;
  }
  
- if (UserAuth::check()) {
-     header('Location: ' . ($redirectTarget !== '' ? $redirectTarget : 'index.php'));
+ if (UserAuth::check() && !in_array((string) ($_GET['mode'] ?? ''), ['verify', 'reset'], true)) {
+     header('Location: ' . ($redirectTarget !== '' ? $redirectTarget : 'account.php'));
      exit;
  }
  
⋮ 43 unchanged lines ⋮
      exit;
  }
  
+ require_once __DIR__ . '/includes/account-tokens.php';
+ require_once __DIR__ . '/includes/account-emails.php';
+ require_once __DIR__ . '/includes/orders.php';
+ 
  $error = null;
- $mode = ($_GET['mode'] ?? 'login') === 'register' ? 'register' : 'login';
+ $notice = null;
+ $requestedMode = (string) ($_GET['mode'] ?? 'login');
+ $mode = in_array($requestedMode, ['login', 'register', 'forgot', 'reset', 'verify'], true) ? $requestedMode : 'login';
+ $resetToken = strtolower(trim((string) ($_REQUEST['token'] ?? '')));
  
+ if ($mode === 'verify') {
+     $verifiedUserId = AccountTokens::consume($resetToken, AccountTokens::PURPOSE_VERIFY);
+     if ($verifiedUserId !== null) {
+         $usersDb = Database::users();
+         $usersDb->prepare('UPDATE user_accounts SET email_verified_at = COALESCE(email_verified_at, NOW()) WHERE id = :id')->execute(['id' => $verifiedUserId]);
+         $emailStatement = $usersDb->prepare('SELECT email FROM user_accounts WHERE id = :id LIMIT 1');
+         $emailStatement->execute(['id' => $verifiedUserId]);
+         $claimed = Orders::claimGuestOrders($verifiedUserId, (string) $emailStatement->fetchColumn());
+         $_SESSION['account_flash'] = ['success', $claimed > 0
+             ? str_replace('{count}', (string) $claimed, Language::get('auth_verified_claimed', 'Email confirmed. We added {count} earlier orders to your account.'))
+             : Language::get('auth_verified', 'Email confirmed. Thank you!')];
+         header('Location: ' . (UserAuth::check() ? 'account.php' : 'user-login.php?mode=login&verified=1'));
+         exit;
+     }
+     $mode = 'login';
+     $error = Language::get('auth_verify_invalid', 'This confirmation link has expired or was already used. Log in and ask for a new one.');
+ }
+ 
+ if (isset($_GET['verified'])) {
+     $notice = Language::get('auth_verified_login', 'Email confirmed. You can log in now.');
+ }
+ if (isset($_GET['reset_done'])) {
+     $notice = Language::get('auth_reset_done', 'Your password was changed. Log in with the new password.');
+ }
+ 
+ if ($mode === 'reset' && AccountTokens::peek($resetToken, AccountTokens::PURPOSE_RESET) === null) {
+     $mode = 'forgot';
+     $error = Language::get('auth_reset_invalid', 'This reset link has expired or was already used. Ask for a new one below.');
+ }
+ 
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      if (!Csrf::verify($_POST['csrf_token'] ?? null)) {
          $error = Language::get('form_security_failed', 'Security check failed, please try again.');
⋮ 35 unchanged lines ⋮
              } else {
                  [$success, $registerError] = UserAuth::register($email, $password, $displayName);
                  if ($success) {
-                     header('Location: ' . ($redirectTarget !== '' ? $redirectTarget : 'index.php'));
+                     $newAccount = UserAuth::user();
+                     if ($newAccount !== null) {
+                         AccountEmails::sendVerification($newAccount);
+                     }
+                     header('Location: ' . ($redirectTarget !== '' ? $redirectTarget : 'account.php'));
                      exit;
                  }
                  $error = $registerError;
                  $mode = 'register';
              }
          }
+ 
+         if ($formAction === 'forgot') {
+             $email = trim((string) ($_POST['email'] ?? ''));
+             if (($wait = LoginThrottle::secondsUntilAllowed('reset', $email)) > 0) {
+                 $error = LoginThrottle::message($wait);
+             } else {
+                 LoginThrottle::recordFailure('reset', $email);
+                 AccountEmails::sendPasswordReset($email);
+                 $notice = Language::get('auth_reset_sent', 'If an account with this email exists, we sent a link to set a new password. Check your inbox and spam folder.');
+             }
+             $mode = 'forgot';
+         }
+ 
+         if ($formAction === 'reset') {
+             $password = (string) ($_POST['password'] ?? '');
+             $passwordConfirm = (string) ($_POST['password_confirm'] ?? '');
+             $mode = 'reset';
+             if (strlen($password) < 8) {
+                 $error = Language::get('auth_password_too_short', 'Password must be at least 8 characters.');
+             } elseif ($password !== $passwordConfirm) {
+                 $error = Language::get('auth_password_mismatch', 'Passwords do not match.');
+             } else {
+                 $resetUserId = AccountTokens::consume($resetToken, AccountTokens::PURPOSE_RESET);
+                 if ($resetUserId === null) {
+                     $mode = 'forgot';
+                     $error = Language::get('auth_reset_invalid', 'This reset link has expired or was already used. Ask for a new one below.');
+                 } else {
+                     $usersDb = Database::users();
+                     $usersDb->prepare('UPDATE user_accounts SET password_hash = :hash, email_verified_at = COALESCE(email_verified_at, NOW()) WHERE id = :id')
+                         ->execute(['hash' => password_hash($password, PASSWORD_DEFAULT), 'id' => $resetUserId]);
+                     $usersDb->prepare('DELETE FROM user_sessions WHERE user_account_id = :id')->execute(['id' => $resetUserId]);
+                     $resetEmail = $usersDb->prepare('SELECT email FROM user_accounts WHERE id = :id');
+                     $resetEmail->execute(['id' => $resetUserId]);
+                     $resetAddress = (string) $resetEmail->fetchColumn();
+                     LoginThrottle::clear('reader', $resetAddress);
+                     Orders::claimGuestOrders($resetUserId, $resetAddress);
+                     header('Location: user-login.php?mode=login&reset_done=1');
+                     exit;
+                 }
+             }
+         }
      }
  }
  
⋮ 44 unchanged lines ⋮
          <?php if ($error !== null): ?>
              <div class="auth-error"><?= htmlspecialchars($error) ?></div>
          <?php endif; ?>
+         <?php if ($notice !== null): ?>
+             <div class="auth-notice"><?= htmlspecialchars($notice) ?></div>
+         <?php endif; ?>
  
-         <?php if ($mode === 'login'): ?>
+         <?php if ($mode === 'forgot'): ?>
+             <form method="post" action="user-login.php?mode=forgot">
+                 <?= Csrf::field() ?>
+                 <?= AntiBot::field('user') ?>
+                 <input type="hidden" name="form_action" value="forgot">
+                 <p class="auth-help"><?= htmlspecialchars(Language::get('auth_forgot_intro', 'Enter the email you use for your account. We will send you a link to set a new password.')) ?></p>
+                 <label><?= htmlspecialchars(Language::get('auth_email', 'Email')) ?></label>
+                 <input type="email" name="email" required autofocus autocomplete="email">
+                 <div class="antibot-box">
+                     <div class="antibot-image"><?= AntiBot::image('user') ?></div>
+                     <label for="antibot-answer"><?= htmlspecialchars(Language::get('auth_security_code', 'Security code')) ?></label>
+                     <input id="antibot-answer" type="text" name="antibot_answer" required inputmode="text" autocomplete="off" maxlength="6" spellcheck="false">
+                 </div>
+                 <button type="submit"><?= htmlspecialchars(Language::get('auth_forgot_button', 'Send the link')) ?></button>
+                 <p class="auth-help"><a href="user-login.php?mode=login"><?= htmlspecialchars(Language::get('auth_back_to_login', 'Back to log in')) ?></a></p>
+             </form>
+         <?php elseif ($mode === 'reset'): ?>
+             <form method="post" action="user-login.php?mode=reset">
+                 <?= Csrf::field() ?>
+                 <?= AntiBot::field('user') ?>
+                 <input type="hidden" name="form_action" value="reset">
+                 <input type="hidden" name="token" value="<?= htmlspecialchars($resetToken, ENT_QUOTES) ?>">
+                 <label><?= htmlspecialchars(Language::get('account_new_password_short', 'New password')) ?></label>
+                 <input type="password" name="password" required minlength="8" autofocus autocomplete="new-password">
+                 <label><?= htmlspecialchars(Language::get('auth_confirm_password', 'Confirm password')) ?></label>
+                 <input type="password" name="password_confirm" required minlength="8" autocomplete="new-password">
+                 <div class="antibot-box">
+                     <div class="antibot-image"><?= AntiBot::image('user') ?></div>
+                     <label for="antibot-answer"><?= htmlspecialchars(Language::get('auth_security_code', 'Security code')) ?></label>
+                     <input id="antibot-answer" type="text" name="antibot_answer" required inputmode="text" autocomplete="off" maxlength="6" spellcheck="false">
+                 </div>
+                 <button type="submit"><?= htmlspecialchars(Language::get('auth_reset_button', 'Save the new password')) ?></button>
+             </form>
+         <?php elseif ($mode === 'login'): ?>
              <form method="post">
                  <?= Csrf::field() ?>
                  <?= AntiBot::field('user') ?>
⋮ 8 unchanged lines ⋮
                      <input id="antibot-answer" type="text" name="antibot_answer" required inputmode="text" autocomplete="off" maxlength="6" spellcheck="false">
                  </div>
                  <button type="submit"><?= htmlspecialchars(Language::get('auth_login_button', 'Log in')) ?></button>
+                 <p class="auth-help"><a href="user-login.php?mode=forgot"><?= htmlspecialchars(Language::get('auth_forgot_link', 'Forgot your password?')) ?></a></p>
              </form>
          <?php else: ?>
              <form method="post">
⋮ 25 unchanged lines ⋮
version.txt Modified +1 -1
- 1.0.0.3
+ 1.1.0.0
webhook.php Modified +38 -90
⋮ 195 unchanged lines ⋮
              markOrderFailed($usersDb, $orderId, $normalizedType === 'checkout.session.expired' ? 'Checkout session expired' : 'Payment failed');
              return;
          }
+ 
+         if ($provider === 'polar' && $normalizedType === 'order.refunded') {
+             processRefundEvent($usersDb, $provider, $data, $orderId);
+             return;
+         }
      }
  
+     if ($provider === 'stripe' && $normalizedType === 'charge.refunded') {
+         processRefundEvent($usersDb, $provider, $data, 0);
+         return;
+     }
+ 
      if ($provider === 'stripe' && $normalizedType === 'checkout.session.completed' && ($data['mode'] ?? '') === 'subscription') {
          processStripeSubscriptionCheckout($usersDb, $data);
          return;
⋮ 62 unchanged lines ⋮
      $customer = $data['customer'] ?? ($data['customer_id'] ?? '');
      $providerCustomerId = is_array($customer) ? (string) ($customer['id'] ?? '') : (string) $customer;
  
-     $updateOrder = $usersDb->prepare(
-         "UPDATE orders SET status = 'paid', provider = :provider, provider_checkout_id = :checkout_id, provider_payment_id = :payment_id, provider_customer_id = :customer_id
-          WHERE id = :id AND status IN ('pending', 'failed')"
-     );
-     $updateOrder->execute([
+     require_once __DIR__ . '/includes/orders.php';
+     Orders::markPaid($orderId, [
          'provider' => $provider,
-         'checkout_id' => $providerCheckoutId !== '' ? $providerCheckoutId : null,
-         'payment_id' => $providerPaymentId !== '' ? $providerPaymentId : null,
-         'customer_id' => $providerCustomerId !== '' ? $providerCustomerId : null,
-         'id' => $orderId,
-     ]);
- 
-     if ($updateOrder->rowCount() === 0) {
-         return;
-     }
- 
-     $usersDb->prepare(
-         "INSERT INTO order_status_history (order_id, status, note) VALUES (:order_id, 'paid', 'Payment confirmed via webhook')"
-     )->execute(['order_id' => $orderId]);
- 
-     $itemsStatement = $usersDb->prepare('SELECT * FROM order_items WHERE order_id = :id');
-     $itemsStatement->execute(['id' => $orderId]);
-     $items = $itemsStatement->fetchAll();
- 
-     $siteDb = Database::site();
- 
-     foreach ($items as $item) {
-         $productId = (int) $item['product_id'];
-         $variantId = $item['variant_id'] !== null ? (int) $item['variant_id'] : null;
-         $quantity = (int) $item['quantity'];
+         'checkout_id' => $providerCheckoutId,
+         'payment_id' => $providerPaymentId,
+         'customer_id' => $providerCustomerId,
+     ], 'Payment confirmed via webhook');
+ }
  
-         $productStatement = $siteDb->prepare('SELECT track_inventory FROM products WHERE id = :id LIMIT 1');
-         $productStatement->execute(['id' => $productId]);
-         $product = $productStatement->fetch();
+ function processRefundEvent(PDO $usersDb, string $provider, array $data, int $orderId): void
+ {
+     require_once __DIR__ . '/includes/orders.php';
  
-         if ($product && (int) $product['track_inventory'] === 1) {
-             $variantUpdated = 0;
-             if ($variantId !== null) {
-                 $variantUpdate = $siteDb->prepare(
-                     'UPDATE product_variants SET stock_quantity = GREATEST(0, stock_quantity - :qty) WHERE id = :id AND stock_quantity IS NOT NULL'
-                 );
-                 $variantUpdate->execute(['qty' => $quantity, 'id' => $variantId]);
-                 $variantUpdated = $variantUpdate->rowCount();
-             }
-             if ($variantUpdated === 0) {
-                 $siteDb->prepare(
-                     'UPDATE products SET stock_quantity = GREATEST(0, stock_quantity - :qty) WHERE id = :id AND stock_quantity IS NOT NULL'
-                 )->execute(['qty' => $quantity, 'id' => $productId]);
-             }
+     if ($orderId <= 0 && $provider === 'stripe') {
+         $paymentIntent = $data['payment_intent'] ?? '';
+         $paymentIntentId = is_array($paymentIntent) ? (string) ($paymentIntent['id'] ?? '') : (string) $paymentIntent;
+         if ($paymentIntentId === '') {
+             return;
          }
- 
-         $siteDb->prepare('UPDATE products SET sales_count = sales_count + :qty WHERE id = :id')
-             ->execute(['qty' => $quantity, 'id' => $productId]);
-     }
- 
-     if (!empty($order['discount_code'])) {
-         $siteDb->prepare(
-             'UPDATE discounts SET times_redeemed = times_redeemed + 1 WHERE UPPER(code) = UPPER(:code)'
-         )->execute(['code' => $order['discount_code']]);
-     }
- 
-     $downloadLinks = [];
-     try {
-         require_once __DIR__ . '/includes/digital-files.php';
-         $downloadLinks = DigitalFiles::grantsForOrder($usersDb, $order, $items);
-     } catch (Throwable $grantException) {
-         error_log('StocketBase webhook: could not create download access — ' . $grantException->getMessage());
-     }
- 
-     try {
-         sendOrderConfirmationEmail($usersDb, $order, $items, $downloadLinks);
-     } catch (Throwable $mailException) {
-         error_log('StocketBase webhook: order confirmation email failed — ' . $mailException->getMessage());
+         $statement = $usersDb->prepare("SELECT id FROM orders WHERE provider = 'stripe' AND provider_payment_id = :payment_id LIMIT 1");
+         $statement->execute(['payment_id' => $paymentIntentId]);
+         $orderId = (int) $statement->fetchColumn();
      }
- }
- 
- function sendOrderConfirmationEmail(PDO $usersDb, array $order, array $items, array $downloadLinks = []): void
- {
-     if (!is_file(__DIR__ . '/includes/mailer.php') || !is_file(__DIR__ . '/includes/mail-templates.php')) {
+     if ($orderId <= 0) {
          return;
      }
  
-     require_once __DIR__ . '/includes/mailer.php';
-     require_once __DIR__ . '/includes/mail-templates.php';
- 
-     if (!class_exists('Mailer') || !class_exists('MailTemplates')) {
-         return;
-     }
+     if ($provider === 'stripe') {
+         $amount = (int) ($data['amount'] ?? 0);
+         $refunded = (int) ($data['amount_refunded'] ?? 0);
+         if (empty($data['refunded']) && ($amount <= 0 || $refunded < $amount)) {
+             Orders::addHistory($orderId, (string) (Orders::find($orderId)['status'] ?? 'paid'), 'Partial refund in Stripe: ' . $refunded . ' of ' . $amount);
  
-     $recipientEmail = (string) ($order['guest_email'] ?? '');
-     if ($recipientEmail === '' && $order['user_account_id'] !== null) {
-         $accountStatement = $usersDb->prepare('SELECT email FROM user_accounts WHERE id = :id LIMIT 1');
-         $accountStatement->execute(['id' => $order['user_account_id']]);
-         $recipientEmail = (string) $accountStatement->fetchColumn();
+             return;
+         }
      }
  
-     if ($recipientEmail !== '') {
-         $email = MailTemplates::orderConfirmationEmail($order, $items, $downloadLinks);
-         Mailer::send($recipientEmail, $email['subject'], $email['html']);
-     }
+     Orders::close($orderId, 'refunded', 'Refunded at ' . ucfirst($provider), null, true);
  }
  
  function findUserAccountId(PDO $usersDb, array $data): ?int
⋮ 20 unchanged lines ⋮
          return null;
      }
  
-     $statement = $usersDb->prepare('SELECT id FROM user_accounts WHERE LOWER(email) = :email LIMIT 1');
+     $statement = $usersDb->prepare("SELECT id FROM user_accounts WHERE LOWER(email) = :email AND status = 'active' AND email_verified_at IS NOT NULL LIMIT 1");
      $statement->execute(['email' => $email]);
      $account = $statement->fetch();
  
⋮ 166 unchanged lines ⋮