<?php
/**
 * Admin: view one folder – list configurations and "Create draft order from this folder".
 */
require __DIR__ . '/config.php';
if (is_file(__DIR__ . '/hubspot-config.php')) {
    require_once __DIR__ . '/hubspot-config.php';
}
require_once __DIR__ . '/admin_config_helpers.php';

 header_remove('X-Frame-Options');
header('Content-Security-Policy: frame-ancestors https://admin.shopify.com https://*.myshopify.com');


function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$folder_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$folder_error = isset($_GET['error']) ? trim((string)$_GET['error']) : '';
$folder_quote_sent = isset($_GET['quote_sent']) && $_GET['quote_sent'] === '1';
$folder_quote_count = isset($_GET['quote_count']) ? (int) $_GET['quote_count'] : 0;
$folder_quote_image_count = isset($_GET['quote_images']) ? (int) $_GET['quote_images'] : 0;
$folder_quote_no_images = isset($_GET['quote_no_images']) && $_GET['quote_no_images'] === '1';
$folder_quote_extra_skipped = isset($_GET['quote_extra_skipped']) && $_GET['quote_extra_skipped'] === '1';
$folder_quote_pdf_url = isset($_GET['quote_pdf_url']) ? trim((string) $_GET['quote_pdf_url']) : '';
$folder_quote_error = isset($_GET['quote_error']) ? trim((string) $_GET['quote_error']) : '';
$folder_draft_created = isset($_GET['draft_created']) && $_GET['draft_created'] === '1';
$folder_invoice_url = isset($_GET['invoice_url']) ? trim((string)$_GET['invoice_url']) : '';
$folder_draft_order_id = isset($_GET['draft_order_id']) ? trim((string)$_GET['draft_order_id']) : '';
if ($folder_draft_order_id !== '') {
    $folder_draft_order_id = rawurldecode($folder_draft_order_id);
}
if ($folder_invoice_url !== '') {
    $folder_invoice_url = rawurldecode($folder_invoice_url);
}
$folder_draft_admin_url = '';
if ($folder_draft_created && $folder_draft_order_id !== '') {
    $numeric_id = preg_replace('/\D/', '', $folder_draft_order_id);
    if ($numeric_id !== '') {
        $store_handle = (defined('SHOPIFY_ADMIN_STORE_HANDLE') && SHOPIFY_ADMIN_STORE_HANDLE !== '')
            ? SHOPIFY_ADMIN_STORE_HANDLE
            : (defined('SHOPIFY_SHOP') ? explode('.', SHOPIFY_SHOP)[0] : '');
        if ($store_handle !== '') {
            $folder_draft_admin_url = 'https://admin.shopify.com/store/' . $store_handle . '/draft_orders/' . $numeric_id;
        }
    }
}
if (!$folder_id) {
    header('Location: folders.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM door_folders WHERE id = ?");
$stmt->execute([$folder_id]);
$folder = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$folder) {
    header('Location: folders.php');
    exit;
}

$folder = admin_load_folder_contact_for_display($folder);

$contact_saved = isset($_GET['contact_saved']) && $_GET['contact_saved'] === '1';
$contact_error = isset($_GET['contact_error']) ? trim((string) $_GET['contact_error']) : '';
$contact_open_id = isset($_GET['contact_open']) ? (int) $_GET['contact_open'] : 0;
if ($contact_open_id <= 0 && ($contact_saved || $contact_error !== '')) {
    $contact_open_id = $folder_id;
}

$stmt = $pdo->prepare("SELECT * FROM door_configurations WHERE folder_id = ? ORDER BY id ASC");
$stmt->execute([$folder_id]);
$configs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$statusLabels = [
    'draft' => 'Draft',
    'in_progress' => 'In progress',
    'awaiting_customer' => 'Awaiting customer',
    'finalized' => 'Finalized',
    'ordered' => 'Ordered',
    'archived' => 'Archived',
];
$admin_current_nav = 'folders';
$admin_app_title = 'Door projects';
$admin_folder_id = $folder_id;
$admin_config_id = 0;
$admin_web_base = admin_normalize_web_path(dirname($_SERVER['SCRIPT_NAME'] ?? ''));
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Project: <?= h($folder['name']) ?></title>
  <?php include __DIR__ . '/includes/admin_layout_styles.php'; ?>
  <?php include __DIR__ . '/includes/folder_contact_styles.php'; ?>
</head>
<body class="admin-app">
  <?php
  $sidebar_file = __DIR__ . '/admin_sidebar.php';
  if (!is_file($sidebar_file)) {
      $sidebar_file = __DIR__ . '/includes/admin_sidebar.php';
  }
  include $sidebar_file;
  ?>
  <main class="admin-main">
  <div class="admin-wrap">
    <header class="admin-page-header">
      <nav class="admin-breadcrumb">
        <a href="folders.php">Projects</a>
        <span>›</span>
        <span><?= h($folder['name']) ?></span>
      </nav>
      <h1 class="admin-page-title"><?= h($folder['name']) ?></h1>
      <p class="admin-page-meta"><?= count($configs) ?> project(s) · Customer: <?= h($folder['customer_email'] ?? '—') ?></p>
    </header>

    <?php if ($contact_saved): ?>
    <div class="admin-alert admin-alert--success">
      <div><strong>Contact saved.</strong> Shopify customer updated and HubSpot contact synced.</div>
    </div>
    <?php endif; ?>
    <?php if ($contact_error !== ''): ?>
    <div class="admin-alert admin-alert--error">
      <div><strong>Contact not saved.</strong> <?= h($contact_error) ?></div>
    </div>
    <?php endif; ?>

    <div class="admin-contact-panel-block">
      <?php
      $return_to = 'folder_detail';
      include __DIR__ . '/includes/folder_contact_panel.php';
      ?>
    </div>

    <?php if ($folder_quote_error !== ''): ?>
    <div class="admin-alert admin-alert--error">
      <div>
        <strong>Quote email failed</strong>
        <?= h($folder_quote_error) ?>
        <p style="margin:0.5rem 0 0 0;">
          <a href="folder_detail.php?id=<?= h($folder_id) ?>">Back to project</a>
        </p>
      </div>
    </div>
    <?php endif; ?>
    <?php if ($folder_quote_sent): ?>
    <div class="admin-alert admin-alert--success">
      <div>
        <strong>Quote emailed via HubSpot</strong>
        <?php if ($folder_quote_count > 0): ?>
        Sent <?= h((string) $folder_quote_count) ?> selected project<?= $folder_quote_count === 1 ? '' : 's' ?> to the customer.
        <?php if ($folder_quote_image_count > 0): ?>
        Included <?= h((string) $folder_quote_image_count) ?> image<?= $folder_quote_image_count === 1 ? '' : 's' ?> (custom or product default).
        <?php elseif ($folder_quote_no_images): ?>
        No product images were on the selected configs (add a custom image on the config edit page if needed).
        <?php endif; ?>
        <?php if ($folder_quote_extra_skipped): ?>
        <span style="display:block;margin-top:0.35rem;font-size:0.85rem;color:#92400e;">
          PDF HubSpot field was skipped (create <code>admin_quote_pdf_url</code> contact property to enable). Summary text was still sent.
        </span>
        <?php endif; ?>
        <?php if ($folder_quote_pdf_url !== ''): ?>
        <span style="display:block;margin-top:0.35rem;font-size:0.85rem;">
          Quote PDF uploaded to Shopify.
          <a href="<?= h($folder_quote_pdf_url) ?>" target="_blank" rel="noopener">View PDF</a>
        </span>
        <?php endif; ?>
        <?php else: ?>
        The quote was sent to the customer.
        <?php endif; ?>
       
      </div>
    </div>
    <?php endif; ?>
    <?php if ($folder_error !== ''): ?>
    <div class="admin-alert admin-alert--error">
      <div>
        <strong>Draft order failed</strong>
        <?= h($folder_error) ?>
        <p style="margin:0.5rem 0 0 0;">
          <a href="create_draft_from_folder.php?folder_id=<?= h($folder_id) ?>&debug=1">Debug (show API response)</a>
        </p>
      </div>
    </div>
    <?php endif; ?>
    <?php if ($folder_draft_created && $folder_draft_admin_url !== ''): ?>
    <div class="admin-alert admin-alert--success">
      <div>
        <strong>Draft order created</strong>
        The draft order is ready. Open it in Shopify Admin to send the invoice to the customer.
        <p style="margin:0.75rem 0 0 0;">
          <a href="<?= h($folder_draft_admin_url) ?>" target="_blank" rel="noopener" class="admin-btn">Open draft order (Admin)</a>
        </p>
      </div>
    </div>
    <?php elseif ($folder_draft_created && $folder_invoice_url !== ''): ?>
    <div class="admin-alert admin-alert--success">
      <div>
        <strong>Draft order created</strong>
        <p style="margin:0.75rem 0 0 0;">
          <a href="<?= h($folder_invoice_url) ?>" target="_blank" rel="noopener" class="admin-btn admin-btn--success">Open invoice (checkout)</a>
        </p>
      </div>
    </div>
    <?php endif; ?>
    <?php if (empty($configs)): ?>
    <div class="admin-actions">
      <span class="admin-btn admin-btn--muted">No projects in this list</span>
    </div>
    <div class="admin-card admin-card--table">
      <div class="admin-card-header">
        <p class="admin-card-title">Projects in this list</p>
      </div>
      <div class="admin-empty admin-empty--icon">
        <div class="admin-empty-icon" aria-hidden="true"></div>
        <p>No projects in this list yet.</p>
      </div>
    </div>
    <?php else: ?>
    <form method="post" action="create_draft_from_folder.php" id="folder-draft-form">
      <input type="hidden" name="folder_id" value="<?= h($folder_id) ?>">
      <input type="hidden" name="admin_base_path" value="<?= h($admin_web_base) ?>">
    <div class="admin-card admin-card--table">
      <div class="folder-actions-bar">
        <button type="submit" class="admin-btn admin-btn--primary" id="folder-create-draft-btn" disabled>Create draft order from selected</button>
        <button
          type="submit"
          class="admin-btn admin-btn--hubspot"
          id="folder-send-quote-btn"
          formaction="send_quote_from_folder.php"
          formmethod="post"
          disabled
          aria-live="polite"
        >
          <svg class="admin-btn__icon admin-btn__icon--mail" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <rect x="2" y="4" width="20" height="16" rx="2"></rect>
            <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"></path>
          </svg>
          <svg class="admin-btn__icon admin-btn__icon--spinner" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true">
            <circle cx="12" cy="12" r="9" stroke-opacity="0.28"></circle>
            <path d="M21 12a9 9 0 0 0-9-9" stroke-linecap="round"></path>
          </svg>
          <span class="admin-btn__text">
            <span class="admin-btn__label-main">Email quote</span>
            <span class="admin-btn__subtitle">via HubSpot</span>
          </span>
        </button>
      </div>
      <div class="admin-card-header">
        <p class="admin-card-title">Projects in this list</p>
      </div>
      <div class="admin-table-wrap">
      <table class="admin-table admin-table--hover">
        <thead>
          <tr>
            <th class="admin-table-col-select">
              <label class="admin-table-select-all" for="folder-select-all-configs">
                <input type="checkbox" id="folder-select-all-configs" aria-label="Select all projects" title="Select all">
              </label>
            </th>
            <th>ID</th>
            <th>Product</th>
            <th>Email</th>
            <th>Status</th>
            <th>Total price</th>
            <th>Created</th>
            <th class="admin-table-col-delete" aria-label="Delete"></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($configs as $c):
            $opts = json_decode($c['options_json'], true) ?: [];
            $productTitle = $opts['_product_title'] ?? '';
            $productImage = $opts['_product_image_url'] ?? '';
            $pillClass = 'admin-pill--' . $c['status'];
            $optionLines = admin_build_options_summary_lines($opts);
          ?>
            <tr>
              <td class="admin-table-col-select">
                <input type="checkbox" class="folder-config-select" name="config_ids[]" value="<?= h($c['id']) ?>" aria-label="Select #<?= h($c['id']) ?>">
              </td>
               <td><a href="configuration_detail.php?id=<?= h($c['id']) ?>&folder_id=<?= h($folder_id) ?>">#<?= h($c['id']) ?></a></td>
              
              <td>
                <div class="admin-product-cell-block">
                  <div class="admin-product-cell">
                    <?php if (!empty($productImage)): ?><img src="<?= h($productImage) ?>" alt=""><?php endif; ?>
                    <span><?= h($productTitle ?: '—') ?></span>
                  </div>
                  <?php if (!empty($optionLines)): ?>
                  <div class="admin-config-options-preview">
                    <button type="button" class="admin-config-options-toggle" aria-expanded="false">
                      <span class="admin-config-options-toggle-icon" aria-hidden="true">+</span>
                      <span>Selected options (<?= count($optionLines) ?>)</span>
                    </button>
                    <ul class="admin-config-options-list" hidden>
                      <?php foreach ($optionLines as $line): ?>
                      <li><strong><?= h($line['label']) ?>:</strong> <?= h($line['value']) ?></li>
                      <?php endforeach; ?>
                    </ul>
                  </div>
                  <?php endif; ?>
                </div>
              </td>
              <td class="admin-email-cell"><?= h($c['customer_email']) ?></td>
              <td><span class="admin-pill <?= h($pillClass) ?>"><?= h($statusLabels[$c['status']] ?? $c['status']) ?></span></td>
              <td class="admin-money">$<?= h(number_format($c['computed_price'], 2)) ?></td>
              <td class="admin-date"><?= h($c['created_at']) ?></td>
              <td class="admin-table-col-delete">
                <button
                  type="submit"
                  class="admin-icon-delete"
                  formaction="<?= h(admin_configuration_remove_url($admin_web_base)) ?>"
                  formmethod="post"
                  name="config_id"
                  value="<?= h($c['id']) ?>"
                  aria-label="Remove #<?= h($c['id']) ?>"
                  onclick="return confirm('Remove #<?= h($c['id']) ?> from this project?');"
                >
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                    <polyline points="3 6 5 6 21 6"></polyline>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                    <line x1="10" y1="11" x2="10" y2="17"></line>
                    <line x1="14" y1="11" x2="14" y2="17"></line>
                  </svg>
                </button>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      </div>
    </div>
    </form>
    <?php endif; ?>
  </div>
  </main>
  <script>
  (function () {
    var selectAll = document.getElementById('folder-select-all-configs');
    var checkboxes = document.querySelectorAll('.folder-config-select');
    var draftBtn = document.getElementById('folder-create-draft-btn');
    var quoteBtn = document.getElementById('folder-send-quote-btn');
    var form = document.getElementById('folder-draft-form');
    var actionsBar = document.querySelector('.folder-actions-bar');
    if (!selectAll || !checkboxes.length || !draftBtn) return;

    function setQuoteLoading(active) {
      if (!quoteBtn) return;
      var label = quoteBtn.querySelector('.admin-btn__label-main');
      if (active) {
        quoteBtn.classList.add('is-loading');
        quoteBtn.setAttribute('aria-busy', 'true');
        quoteBtn.disabled = true;
        if (label) label.textContent = 'Sending quote...';
        if (actionsBar) actionsBar.classList.add('is-submitting');
        draftBtn.disabled = true;
        // Do not disable row checkboxes: disabled inputs are omitted from POST (config_ids[]).
        if (selectAll) selectAll.disabled = true;
      }
    }

    if (form && quoteBtn) {
      form.addEventListener('submit', function (e) {
        var submitter = e.submitter;
        if (!submitter || submitter.id !== 'folder-send-quote-btn') return;
        if (quoteBtn.classList.contains('is-loading')) {
          e.preventDefault();
          return;
        }
        setQuoteLoading(true);
      });
    }

    function updateSelectionButtons() {
      if (quoteBtn && quoteBtn.classList.contains('is-loading')) return;
      var anyChecked = false;
      checkboxes.forEach(function (cb) {
        if (cb.checked) anyChecked = true;
      });
      draftBtn.disabled = !anyChecked;
      if (quoteBtn) quoteBtn.disabled = !anyChecked;
    }

    selectAll.addEventListener('change', function () {
      checkboxes.forEach(function (cb) {
        cb.checked = selectAll.checked;
      });
      updateSelectionButtons();
    });

    checkboxes.forEach(function (cb) {
      cb.addEventListener('change', function () {
        if (!cb.checked) {
          selectAll.checked = false;
        } else {
          var allChecked = true;
          checkboxes.forEach(function (item) {
            if (!item.checked) allChecked = false;
          });
          selectAll.checked = allChecked;
        }
        updateSelectionButtons();
      });
    });

    updateSelectionButtons();
  })();

  document.querySelectorAll('.admin-config-options-toggle').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var preview = btn.closest('.admin-config-options-preview');
      if (!preview) return;
      var list = preview.querySelector('.admin-config-options-list');
      var icon = btn.querySelector('.admin-config-options-toggle-icon');
      if (!list || !icon) return;
      var open = list.hasAttribute('hidden');
      if (open) {
        list.removeAttribute('hidden');
        icon.textContent = '−';
        btn.setAttribute('aria-expanded', 'true');
      } else {
        list.setAttribute('hidden', '');
        icon.textContent = '+';
        btn.setAttribute('aria-expanded', 'false');
      }
    });
  });
  </script>
</body>
</html>
