<?php
/**
 * Seller Marketing → Notifications (Commerce Growth Engine)
 */
require_once __DIR__ . '/_init.php';
require_once dirname(__DIR__) . '/includes/commerce/SgCommercePush.php';
require_once dirname(__DIR__) . '/includes/notifications/SgWebPush.php';

$seller_page_title = 'Notifications';
$seller_current_page = 'notifications';
$sg_webapp_shell = true;
$sg_product_create_shell = true;
$sg_hide_app_header = true;

$conn = getDBConnection();
$audience = ['followers' => 0, 'push_subscribers' => 0, 'repeat_customers' => 0];
$analytics = ['delivered' => 0, 'opened' => 0, 'ctr' => 0, 'sales' => 0, 'revenue' => 0, 'campaigns' => 0];
$recommend = ['day' => 'Friday', 'time' => '7:45 PM', 'expected_opens' => 0, 'expected_clicks' => 0, 'expected_purchases' => 0];
$limits = ['daily' => 1, 'used' => 0, 'remaining' => 1];
$campaigns = [];
$automations = [];
$templates = sg_commerce_push_templates();
$audiences = sg_commerce_push_audiences();
$push_ok = sg_web_push_is_configured();

if ($conn) {
    sg_commerce_push_bootstrap($conn);
    sg_commerce_push_ensure_automations($conn, (int)$seller_id);
    $audience = sg_commerce_push_audience_stats($conn, (int)$seller_id);
    $analytics = sg_commerce_push_analytics_summary($conn, (int)$seller_id);
    $recommend = sg_commerce_push_recommend_send_time($conn, (int)$seller_id);
    $plan = (string)($seller_plan ?? $_SESSION['seller_plan'] ?? 'trial');
    if (isset($seller) && is_array($seller) && !empty($seller['plan'])) {
        $plan = (string)$seller['plan'];
    } else {
        $pr = @$conn->query('SELECT plan FROM sellers WHERE id = ' . (int)$seller_id . ' LIMIT 1');
        if ($pr && ($prow = $pr->fetch_assoc())) {
            $plan = (string)$prow['plan'];
        }
    }
    $limits['daily'] = sg_commerce_push_daily_limit($plan);
    $limits['used'] = sg_commerce_push_campaigns_sent_today($conn, (int)$seller_id);
    $limits['remaining'] = max(0, $limits['daily'] - $limits['used']);

    $sid = (int)$seller_id;
    $cr = @$conn->query(
        "SELECT id, title, message, audience, status, sent_at, delivered_count, opened_count, clicked_count, sales_count, revenue_ghs, source, created_at
         FROM store_push_campaigns WHERE seller_id = $sid ORDER BY id DESC LIMIT 30"
    );
    if ($cr) {
        while ($row = $cr->fetch_assoc()) {
            $campaigns[] = $row;
        }
    }
    $ar = @$conn->query(
        "SELECT id, automation_type, enabled, title_tpl, message_tpl, delay_minutes, audience, last_run_at
         FROM store_push_automations WHERE seller_id = $sid ORDER BY id ASC"
    );
    if ($ar) {
        while ($row = $ar->fetch_assoc()) {
            $automations[] = $row;
        }
    }
    $conn->close();
}

$store_public = '';
if (function_exists('sg_seller_resolve_store_urls')) {
    $urls = sg_seller_resolve_store_urls((string)$seller_slug, null, (int)$seller_id);
    $store_public = (string)($urls['public'] ?? '');
}

require_once __DIR__ . '/header.php';
?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/sg-seller-notifications.css?v=1">

<div class="sg-sn" id="sgSellerNotifications"
     data-api="/api/seller/commerce-push.php"
     data-store-url="<?php echo htmlspecialchars($store_public); ?>"
     data-store-name="<?php echo htmlspecialchars((string)$store_name); ?>">

  <header class="sg-sn-top">
    <a href="index.php" class="sg-sn-back" data-sg-back aria-label="Back"><i class="fas fa-chevron-left"></i></a>
    <div class="sg-sn-brand">
      <span>Marketing</span>
      <strong>Notifications</strong>
    </div>
    <a href="share-store.php" class="sg-sn-share" title="Share store"><i class="fas fa-qrcode"></i></a>
  </header>

  <?php if (!$push_ok): ?>
  <div class="sg-sn-banner sg-sn-banner--warn">Web Push is not fully configured on this server. Contact support if campaigns fail to deliver.</div>
  <?php endif; ?>

  <section class="sg-sn-stats">
    <div class="sg-sn-stat">
      <strong><?php echo number_format((int)$audience['followers']); ?></strong>
      <span>Followers</span>
    </div>
    <div class="sg-sn-stat">
      <strong><?php echo number_format((int)$audience['push_subscribers']); ?></strong>
      <span>Push Subscribers</span>
    </div>
    <div class="sg-sn-stat">
      <strong><?php echo number_format((int)$audience['repeat_customers']); ?></strong>
      <span>Repeat Customers</span>
    </div>
  </section>

  <section class="sg-sn-perf">
    <h2>Campaign Performance</h2>
    <div class="sg-sn-perf-grid">
      <div><strong><?php echo number_format((int)$analytics['delivered']); ?></strong><span>Delivered</span></div>
      <div><strong><?php echo number_format((int)$analytics['opened']); ?></strong><span>Opened</span></div>
      <div><strong><?php echo htmlspecialchars((string)$analytics['ctr']); ?>%</strong><span>CTR</span></div>
      <div><strong><?php echo number_format((int)$analytics['sales']); ?></strong><span>Sales</span></div>
      <div class="sg-sn-perf-wide"><strong>GH₵<?php echo number_format((float)$analytics['revenue'], 0); ?></strong><span>Revenue</span></div>
    </div>
  </section>

  <section class="sg-sn-ai">
    <h2>AI Send Time</h2>
    <p class="sg-sn-lead">Recommended send time based on opens, clicks, and purchase patterns.</p>
    <div class="sg-sn-ai-card">
      <div class="sg-sn-ai-when">
        <span><?php echo htmlspecialchars((string)$recommend['day']); ?></span>
        <strong><?php echo htmlspecialchars((string)$recommend['time']); ?></strong>
      </div>
      <div class="sg-sn-ai-expect">
        <div><strong><?php echo number_format((int)$recommend['expected_opens']); ?></strong><span>Expected opens</span></div>
        <div><strong><?php echo number_format((int)$recommend['expected_clicks']); ?></strong><span>Expected clicks</span></div>
        <div><strong><?php echo number_format((int)$recommend['expected_purchases']); ?></strong><span>Expected purchases</span></div>
      </div>
    </div>
  </section>

  <section class="sg-sn-compose" id="sgSnCompose">
    <h2>Create Campaign</h2>
    <p class="sg-sn-limit"><?php echo (int)$limits['remaining']; ?> of <?php echo (int)$limits['daily']; ?> campaigns left today</p>

    <label class="sg-sn-label">Template</label>
    <select id="sgSnTemplate" class="sg-sn-input">
      <option value="">Custom</option>
      <?php foreach ($templates as $key => $tpl): ?>
      <option value="<?php echo htmlspecialchars($key); ?>"
              data-title="<?php echo htmlspecialchars($tpl['title']); ?>"
              data-message="<?php echo htmlspecialchars($tpl['message']); ?>">
        <?php echo htmlspecialchars($tpl['label']); ?>
      </option>
      <?php endforeach; ?>
    </select>

    <label class="sg-sn-label">Title</label>
    <input type="text" id="sgSnTitle" class="sg-sn-input" maxlength="120" placeholder="Weekend Sale" value="">

    <label class="sg-sn-label">Message</label>
    <textarea id="sgSnMessage" class="sg-sn-input" maxlength="500" rows="3" placeholder="Jordan 4 now 25% OFF. Today only."></textarea>

    <label class="sg-sn-label">Image URL (optional)</label>
    <input type="url" id="sgSnImage" class="sg-sn-input" placeholder="https://…">

    <label class="sg-sn-label">Destination URL</label>
    <input type="url" id="sgSnUrl" class="sg-sn-input" value="<?php echo htmlspecialchars($store_public); ?>" placeholder="https://…">

    <label class="sg-sn-label">Audience</label>
    <select id="sgSnAudience" class="sg-sn-input">
      <?php foreach ($audiences as $k => $label): ?>
      <option value="<?php echo htmlspecialchars($k); ?>"><?php echo htmlspecialchars($label); ?></option>
      <?php endforeach; ?>
    </select>

    <label class="sg-sn-label">Schedule (optional)</label>
    <input type="datetime-local" id="sgSnSchedule" class="sg-sn-input">

    <div class="sg-sn-preview" id="sgSnPreview" aria-live="polite">
      <div class="sg-sn-preview-push">
        <img src="/assets/img/sg-push-icon-192.png" alt="" width="36" height="36">
        <div>
          <strong id="sgSnPrevTitle">Weekend Sale</strong>
          <p id="sgSnPrevMsg">Jordan 4 now 25% OFF. Today only.</p>
          <em>Shop Now</em>
        </div>
      </div>
    </div>

    <div class="sg-sn-actions">
      <button type="button" class="sg-sn-btn sg-sn-btn--ghost" id="sgSnSaveDraft">Save Draft</button>
      <button type="button" class="sg-sn-btn sg-sn-btn--primary" id="sgSnSend">Send</button>
    </div>
    <p class="sg-sn-status" id="sgSnStatus" hidden></p>
  </section>

  <section class="sg-sn-auto">
    <h2>AI Marketing Automation</h2>
    <p class="sg-sn-lead">Your AI employee sends these automatically when customers need a nudge.</p>
    <div class="sg-sn-auto-list">
      <?php
      $autoLabels = [
          'cart_abandon' => 'Cart Abandonment',
          'wishlist' => 'Wishlist Reminder',
          'price_drop' => 'Price Drop',
          'back_in_stock' => 'Back in Stock',
          'new_arrival' => 'New Arrival',
          'flash_sale' => 'Flash Sale',
          'order_update' => 'Order Updates',
      ];
      foreach ($automations as $auto):
          $type = (string)$auto['automation_type'];
          $label = $autoLabels[$type] ?? ucwords(str_replace('_', ' ', $type));
      ?>
      <div class="sg-sn-auto-row" data-type="<?php echo htmlspecialchars($type); ?>">
        <div>
          <strong><?php echo htmlspecialchars($label); ?></strong>
          <small><?php echo htmlspecialchars((string)$auto['title_tpl']); ?> — <?php echo htmlspecialchars((string)$auto['message_tpl']); ?></small>
        </div>
        <label class="sg-sn-switch">
          <input type="checkbox" class="sg-sn-auto-toggle" <?php echo !empty($auto['enabled']) ? 'checked' : ''; ?>>
          <span></span>
        </label>
      </div>
      <?php endforeach; ?>
    </div>
  </section>

  <section class="sg-sn-history">
    <h2>Recent Campaigns</h2>
    <?php if ($campaigns === []): ?>
    <p class="sg-sn-empty">No campaigns yet. Create your first notification above.</p>
    <?php else: ?>
    <div class="sg-sn-hist-list">
      <?php foreach ($campaigns as $c): ?>
      <article class="sg-sn-hist-item">
        <div class="sg-sn-hist-main">
          <strong><?php echo htmlspecialchars((string)$c['title']); ?></strong>
          <p><?php echo htmlspecialchars((string)$c['message']); ?></p>
          <small>
            <?php echo htmlspecialchars((string)$c['status']); ?>
            · <?php echo htmlspecialchars((string)$c['audience']); ?>
            <?php if (!empty($c['sent_at'])): ?> · <?php echo htmlspecialchars(date('M j, g:ia', strtotime((string)$c['sent_at']))); endif; ?>
            <?php if (($c['source'] ?? '') === 'automation'): ?> · AI<?php endif; ?>
          </small>
        </div>
        <div class="sg-sn-hist-metrics">
          <span><?php echo (int)$c['delivered_count']; ?> sent</span>
          <span><?php echo (int)$c['opened_count']; ?> opens</span>
          <span><?php echo (int)$c['clicked_count']; ?> clicks</span>
        </div>
      </article>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </section>
</div>

<script src="/assets/js/sg-seller-notifications.js?v=1" defer></script>
<?php require_once __DIR__ . '/footer.php'; ?>
