<?php
/**
 * فایل واسط فروشگاه — نسخه‌ی 3.59.126
 * ------------------------------------------------------------
 * این فایل را روی هاست سایتت بگذار (مثلاً کنار index.php با نام shop-proxy.php) و چهار خط زیر را پر کن.
 * بعد هر جای سایت که خواستی فروشگاه بیاید، این دو خط را بگذار:
 *
 *   <div data-cshop></div>
 *   <script src="/shop-proxy.php?js=1" data-api="/shop-proxy.php?p={p}" data-proxy="1" defer></script>
 *
 * مزیت‌ها: کلید محرمانه روی سرور خودت می‌ماند، آدرس سرور پنل در صفحه دیده نمی‌شود، و پرداخت آنلاین با درگاه و مرچنت خودت انجام می‌شود.
 * (درگاه‌های ایرانی فقط از هاست ایرانی و دامنه‌ی ثبت‌شده جواب می‌دهند؛ این فایل باید روی همان دامنه‌ای باشد که در درگاه ثبت کرده‌ای.)
 */
$CS_CONFIG = [
  'public_key' => '',            // کلید فروشگاه (pk_…) — از «API ← فروشگاه سایت ← کلید فروشگاه»
  'secret_key' => '',            // کلید API با دسترسی «فروشگاه» (tsk_…) — فقط برای پرداخت آنلاین و درگاه خودت لازم است
  'gateway'    => '',            // '' (بدون درگاه) یا 'zibal' یا 'zarinpal'
  'merchant'   => '',            // مرچنت درگاه خودت
  'cloudflare' => false,         // اگر سایتت پشت Cloudflare است true کن (برای آی‌پی واقعی مشتری)
  'api'        => 'https://tishtar.site/api/v1',     // دست نزن
];
/* ============ از این‌جا به بعد را تغییر نده ============ */
/**
 * هسته‌ی مشترک «فایل واسط فروشگاه» و افزونه‌ی وردپرس — نسخه‌ی 3.59.126
 * درخواست‌های فروشگاه آماده (مرورگر مشتری) را با کلیدهای شما به سرور پنل می‌رساند، و درگاه زیبال/زرین‌پال را با مرچنت خود شما اجرا می‌کند.
 * کلید محرمانه فقط روی سرور شما می‌ماند و به مرورگر نمی‌رسد.
 */
if (!class_exists('CS_Core')) {
class CS_Core {
  const V = '3.59.126';
  public $c;
  public $zibal = 'https://gateway.zibal.ir';
  public $zarin = 'https://payment.zarinpal.com';
  /** c: api, public_key, secret_key, gateway (zibal|zarinpal|''), merchant, self (آدرس همین واسط با ?p={p})، http (اختیاری: تابع ارسال) */
  public function __construct(array $c) {
    $this->c = $c + ['api' => '', 'public_key' => '', 'secret_key' => '', 'gateway' => '', 'merchant' => '', 'self' => '', 'http' => null];
    $this->c['api'] = rtrim((string)$this->c['api'], '/');
    if (getenv('CS_ZIBAL')) $this->zibal = rtrim(getenv('CS_ZIBAL'), '/');
    if (getenv('CS_ZARIN')) $this->zarin = rtrim(getenv('CS_ZARIN'), '/');
  }
  public function ready() { return (bool)preg_match('/^pk_\d+_/', (string)$this->c['public_key']) && preg_match('#^https?://#', (string)$this->c['api']); }
  public function gw() { $g = (string)$this->c['gateway']; return in_array($g, ['zibal', 'zarinpal'], true) && trim((string)$this->c['merchant']) !== '' && $this->has_secret() ? $g : ''; }
  public function has_secret() { return (bool)preg_match('/^tsk_\d+_[a-z0-9]{6}[A-Za-z0-9]{32}$/', (string)$this->c['secret_key']); }

  /** ارسال HTTP ← [کد، بدنه] */
  public function http($method, $url, array $headers, $body = null, $timeout = 25) {
    if (is_callable($this->c['http'])) return call_user_func($this->c['http'], $method, $url, $headers, $body, $timeout);
    $ch = curl_init($url);
    $o = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_CONNECTTIMEOUT => 8, CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_HTTPHEADER => $headers, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS | CURLPROTO_HTTP, CURLOPT_USERAGENT => 'Shop-Proxy/' . self::V];
    if ($body !== null) $o[CURLOPT_POSTFIELDS] = $body;
    curl_setopt_array($ch, $o); $r = curl_exec($ch); $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch);
    return [$r === false ? 0 : $code, (string)$r];
  }
  private function j($r) { $j = json_decode((string)$r[1], true); return is_array($j) ? $j : null; }
  private function fail($code, $msg, $st = 502) { return [$st, ['ok' => false, 'error' => ['code' => $code, 'message' => $msg]]]; }

  /** درخواست به API عمومی فروشگاه */
  public function pub($method, $path, $body = null, $tok = '', $ip = '') {
    $h = ['Accept: application/json', 'X-Public-Key: ' . $this->c['public_key']];
    if ($this->has_secret()) $h[] = 'Authorization: Bearer ' . $this->c['secret_key'];
    if ($tok !== '') $h[] = 'X-Customer-Token: ' . $tok;
    if ($ip !== '') $h[] = 'X-Client-IP: ' . $ip;
    if ($body !== null) $h[] = 'Content-Type: application/json';
    return $this->http($method, $this->c['api'] . '/pub/' . $path, $h, $body);
  }
  /** درخواست به API فروشگاه با کلید محرمانه */
  public function rest($method, $path, array $body = null) {
    $h = ['Accept: application/json', 'Authorization: Bearer ' . $this->c['secret_key']];
    if ($body !== null) $h[] = 'Content-Type: application/json';
    return $this->http($method, $this->c['api'] . '/' . $path, $h, $body !== null ? json_encode($body) : null);
  }

  /**
   * اجرای یک درخواست مرورگر ← [کد، آرایه‌ی پاسخ]
   * $p: مسیر (store، orders، orders/ID/receipt، pay/ID، …)
   */
  public function handle($method, $p, $raw, $tok, $ip) {
    $method = strtoupper($method); $p = trim((string)$p, '/');
    if (!$this->ready()) return $this->fail('not_configured', 'فروشگاه هنوز تنظیم نشده.', 503);
    if (!preg_match('#^[A-Za-z0-9_\-]+(/[A-Za-z0-9_\-]+){0,3}$#', $p)) return $this->fail('not_found', 'مسیر پیدا نشد.', 404);
    if (!in_array($method, ['GET', 'POST'], true)) return $this->fail('method_not_allowed', 'روش درست نیست.', 405);
    if (strlen((string)$raw) > 12 * 1024 * 1024) return $this->fail('too_large', 'حجم درخواست زیاد است.', 413);
    $tok = preg_match('/^ct_c[a-z0-9]{7}_[A-Za-z0-9]{28}$/', (string)$tok) ? (string)$tok : '';
    if (preg_match('#^pay/([A-Za-z0-9_\-]{1,40})$#', $p, $m)) { if ($method !== 'POST') return $this->fail('method_not_allowed', 'روش درست نیست.', 405); $b = json_decode((string)$raw, true); return $this->pay($m[1], $tok, is_array($b) ? (string)($b['return_url'] ?? '') : ''); }
    $r = $this->pub($method, $p, $method === 'POST' ? (string)$raw : null, $tok, $ip);
    $j = $this->j($r);
    if (!$j) return $this->fail('upstream', 'سرور فروشگاه پاسخ نداد؛ کمی بعد دوباره امتحان کن.');
    if ($p === 'store' && !empty($j['ok'])) {   // درگاه فقط وقتی که مرچنت تنظیم شده
      $gw = $this->gw() !== '';
      $f = function ($ms) use ($gw) { return array_values(array_filter((array)$ms, function ($x) use ($gw) { return $x !== 'ext' || $gw; })); };
      $j['data']['methods'] = $f($j['data']['methods'] ?? []); $j['data']['gateway'] = $gw;
      foreach ((array)($j['data']['plans'] ?? []) as $i => $pl) $j['data']['plans'][$i]['methods'] = $f($pl['methods'] ?? []);
    }
    return [$r[0] ?: 502, $j];
  }

  /* ---------------- درگاه ---------------- */
  private function key() { return hash('sha256', 'cs-gw|' . $this->c['secret_key']); }
  private function b64e($s) { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }
  private function b64d($s) { return base64_decode(strtr((string)$s, '-_', '+/'), true); }
  public function seal(array $a) { $p = $this->b64e(json_encode($a)); return $p . '.' . substr(hash_hmac('sha256', $p, $this->key()), 0, 32); }
  public function unseal($s) {
    $x = explode('.', (string)$s); if (count($x) !== 2 || !hash_equals(substr(hash_hmac('sha256', $x[0], $this->key()), 0, 32), $x[1])) return null;
    $a = json_decode((string)$this->b64d($x[0]), true); return is_array($a) && (int)($a['t'] ?? 0) > time() - 86400 ? $a : null;
  }
  /** آدرس بازگشت فقط روی همین دامنه (جلوگیری از تغییر مسیر به سایت دیگر) */
  public function safe_return($u) {
    $self = parse_url((string)$this->c['self']); $x = parse_url((string)$u);
    if (!$x || empty($x['host']) || !in_array($x['scheme'] ?? '', ['http', 'https'], true) || strcasecmp($x['host'], (string)($self['host'] ?? '')) !== 0) return '';
    return strtok((string)$u, '#');
  }
  private function back($ret, $oid, $st) {
    $u = preg_replace('/([?&])cs_(o|s|ref)=[^&]*/', '$1', $ret); $u = rtrim(str_replace(['?&', '&&'], ['?', '&'], $u), '?&');
    return $u . (strpos($u, '?') === false ? '?' : '&') . 'cs_o=' . rawurlencode($oid) . '&cs_s=' . $st;
  }
  private function order($oid) { $j = $this->j($this->rest('GET', 'shop/orders/' . rawurlencode($oid))); return $j && !empty($j['ok']) ? $j['data'] : null; }

  public function pay($oid, $tok, $ret) {
    $g = $this->gw(); if ($g === '') return $this->fail('no_gateway', 'پرداخت آنلاین فعال نیست.', 409);
    if ($tok === '') return $this->fail('customer_unauthorized', 'اول سفارش ثبت کن.', 401);
    $ret = $this->safe_return($ret); if ($ret === '') return $this->fail('validation', 'آدرس بازگشت درست نیست.', 422);
    $j = $this->j($this->pub('GET', 'orders/' . rawurlencode($oid), null, $tok));      // مالکیت سفارش با توکن مشتری
    if (!$j || empty($j['ok'])) return [404, $j ?: ['ok' => false, 'error' => ['code' => 'not_found', 'message' => 'سفارش پیدا نشد.']]];
    $o = $j['data']['order'];
    if (($o['method'] ?? '') !== 'ext' || ($o['status'] ?? '') !== 'awaiting_payment') return $this->fail('not_open', 'این سفارش منتظر پرداخت آنلاین نیست.', 409);
    $rial = (int)$o['amount_toman'] * 10;
    $cb = $this->c['self']; $cb = str_replace('{p}', 'cb', $cb);
    $cb .= (strpos($cb, '?') === false ? '?' : '&') . 'cs=' . $this->seal(['o' => $o['id'], 'r' => $ret, 'g' => $g, 'a' => $rial, 't' => time()]);
    $desc = 'سفارش ' . $o['id'];
    if ($g === 'zibal') {
      $r = $this->j($this->http('POST', $this->zibal . '/v1/request', ['Content-Type: application/json'], json_encode(['merchant' => $this->c['merchant'], 'amount' => $rial, 'callbackUrl' => $cb, 'orderId' => $o['id'], 'description' => $desc])));
      if (!$r || (int)($r['result'] ?? 0) !== 100) return $this->fail('gateway', 'درگاه پاسخ نداد (' . (int)($r['result'] ?? 0) . ')؛ کمی بعد دوباره امتحان کن.');
      return [200, ['ok' => true, 'data' => ['url' => $this->zibal . '/start/' . rawurlencode((string)$r['trackId'])]]];
    }
    $r = $this->j($this->http('POST', $this->zarin . '/pg/v4/payment/request.json', ['Content-Type: application/json', 'Accept: application/json'], json_encode(['merchant_id' => $this->c['merchant'], 'amount' => $rial, 'currency' => 'IRR', 'callback_url' => $cb, 'description' => $desc, 'metadata' => ['order_id' => $o['id']]])));
    if (!$r || (int)($r['data']['code'] ?? 0) !== 100 || empty($r['data']['authority'])) return $this->fail('gateway', 'درگاه پاسخ نداد؛ کمی بعد دوباره امتحان کن.');
    return [200, ['ok' => true, 'data' => ['url' => $this->zarin . '/pg/StartPay/' . rawurlencode((string)$r['data']['authority'])]]];
  }

  /** بازگشت از درگاه ← آدرسی که مشتری به آن برمی‌گردد */
  public function callback(array $q) {
    $s = $this->unseal($q['cs'] ?? ''); if (!$s) return '';
    $oid = (string)$s['o']; $ret = (string)$s['r']; $rial = (int)$s['a']; $ref = '';
    if ($s['g'] === 'zibal') {
      $tr = preg_replace('/\D/', '', (string)($q['trackId'] ?? ''));
      if ($tr === '' || (string)($q['success'] ?? '') !== '1') return $this->back($ret, $oid, 'fail');
      $r = $this->j($this->http('POST', $this->zibal . '/v1/verify', ['Content-Type: application/json'], json_encode(['merchant' => $this->c['merchant'], 'trackId' => (int)$tr])));
      $res = (int)($r['result'] ?? 0);
      if ($res === 201) {   // قبلاً تأیید شده؛ مبلغ و سفارش را از خود درگاه بپرس
        $r = $this->j($this->http('POST', $this->zibal . '/v1/inquiry', ['Content-Type: application/json'], json_encode(['merchant' => $this->c['merchant'], 'trackId' => (int)$tr])));
        if (!$r || (int)($r['result'] ?? 0) !== 100 || !in_array((int)($r['status'] ?? 0), [1, 2], true)) return $this->back($ret, $oid, 'fail');
      } elseif ($res !== 100) return $this->back($ret, $oid, 'fail');
      if ((int)($r['amount'] ?? 0) !== $rial || (isset($r['orderId']) && (string)$r['orderId'] !== '' && (string)$r['orderId'] !== $oid)) return $this->back($ret, $oid, 'fail');
      $ref = 'zb' . $tr;
    } else {
      $au = preg_replace('/[^A-Za-z0-9]/', '', (string)($q['Authority'] ?? ''));
      if ($au === '' || (string)($q['Status'] ?? '') !== 'OK') return $this->back($ret, $oid, 'fail');
      $r = $this->j($this->http('POST', $this->zarin . '/pg/v4/payment/verify.json', ['Content-Type: application/json', 'Accept: application/json'], json_encode(['merchant_id' => $this->c['merchant'], 'amount' => $rial, 'authority' => $au])));
      $code = (int)($r['data']['code'] ?? 0);
      if ($code !== 100 && $code !== 101) return $this->back($ret, $oid, 'fail');
      $ref = 'zp' . ((string)($r['data']['ref_id'] ?? '') ?: $au);
    }
    $o = $this->order($oid);
    if (!$o || (int)$o['amount_toman'] * 10 !== $rial) return $this->back($ret, $oid, 'fail');
    for ($i = 0; $i < 3; $i++) {   // پول گرفته شده؛ ثبت را تا سه بار امتحان کن
      $p = $this->j($this->rest('POST', 'shop/orders/' . rawurlencode($oid) . '/paid', ['ref' => substr($ref, 0, 80), 'amount_toman' => (int)($rial / 10), 'gateway' => $s['g']]));
      if ($p && !empty($p['ok'])) return $this->back($ret, $oid, 'ok');
      if ($p && isset($p['error']['code'])) { if (in_array($p['error']['code'], ['duplicate_ref', 'amount_mismatch', 'wrong_method', 'not_found'], true)) return $this->back($ret, $oid, 'fail'); break; }
      if ($i < 2) sleep(1);
    }
    return $this->back($ret, $oid, 'paid') . '&cs_ref=' . rawurlencode($ref);
  }
}
}

error_reporting(0);
function csp_self() {
  $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https' || (int)($_SERVER['SERVER_PORT'] ?? 0) === 443;
  return ($https ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . strtok((string)($_SERVER['REQUEST_URI'] ?? '/'), '?');
}
function csp_ip($cf) {
  $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
  if ($cf && !empty($_SERVER['HTTP_CF_CONNECTING_IP']) && filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP)) $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
  return $ip;
}
function csp_page($t, $m) {
  http_response_code(400); header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: no-store');
  echo '<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>' . htmlspecialchars($t) . '</title></head><body style="font-family:Tahoma,sans-serif;display:grid;place-items:center;min-height:100vh;margin:0;padding:16px;box-sizing:border-box"><div style="max-width:420px;text-align:center;line-height:1.9"><h1 style="font-size:19px">' . htmlspecialchars($t) . '</h1><p>' . htmlspecialchars($m) . '</p><a href="/">بازگشت به سایت</a></div></body></html>';
  exit;
}
$CS = new CS_Core($CS_CONFIG + ['self' => csp_self() . '?p={p}']);
header('X-Robots-Tag: noindex'); header('X-Content-Type-Options: nosniff');

// ۱) فایل فروشگاه آماده (یک روز در حافظه‌ی موقت نگه داشته می‌شود)
if (isset($_GET['js'])) {
  $f = rtrim(sys_get_temp_dir(), '/\\') . '/cshop-' . substr(md5($CS_CONFIG['api']), 0, 8) . '.js';
  $js = is_file($f) && filemtime($f) > time() - 86400 ? (string)file_get_contents($f) : '';
  if ($js === '') {
    [$c, $b] = $CS->http('GET', preg_replace('#/api/v1$#', '', $CS->c['api']) . '/assets/js/cshop.js', ['Accept: */*'], null, 15);
    if ($c === 200 && strpos($b, 'CShop') !== false) { $js = $b; @file_put_contents($f . '.tmp', $b) && @rename($f . '.tmp', $f); }
    elseif (is_file($f)) $js = (string)file_get_contents($f);
  }
  header('Content-Type: application/javascript; charset=utf-8'); header('Cache-Control: public, max-age=3600');
  echo $js !== '' ? $js : 'console.warn("shop: widget unavailable");';
  exit;
}
// ۲) بازگشت از درگاه
if (isset($_GET['cs'])) {
  $u = $CS->callback($_GET);
  if ($u === '') csp_page('لینک نامعتبر', 'این لینک بازگشت معتبر نیست یا منقضی شده.');
  header('Cache-Control: no-store'); header('Location: ' . $u, true, 302); exit;
}
// ۳) درخواست‌های فروشگاه
header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store');
$m = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
if ($m === 'OPTIONS') { http_response_code(204); exit; }
$o = (string)($_SERVER['HTTP_ORIGIN'] ?? '');
if ($o !== '' && strcasecmp((string)parse_url($o, PHP_URL_HOST), (string)parse_url(csp_self(), PHP_URL_HOST)) !== 0) { http_response_code(403); echo json_encode(['ok' => false, 'error' => ['code' => 'origin_not_allowed', 'message' => 'دسترسی مجاز نیست.']]); exit; }
$raw = $m === 'POST' ? (string)file_get_contents('php://input', false, null, 0, 12 * 1024 * 1024 + 1) : null;
[$code, $res] = $CS->handle($m, (string)($_GET['p'] ?? ''), $raw, (string)($_SERVER['HTTP_X_CUSTOMER_TOKEN'] ?? ''), csp_ip(!empty($CS_CONFIG['cloudflare'])));
http_response_code($code);
echo json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
