<?php
// ============================================================
//  faqs.php  —  Author: Frequently Asked Questions
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

$user       = getCurrentUser();
$user_id    = $user['user_id'];
$pageTitle  = 'FAQs';
$activePage = 'faqs';

require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── Wrapper ──────────────────────────────────────────────── */
.faq-wrap { padding: 24px 28px 60px; }

/* ── Page header ──────────────────────────────────────────── */
.faq-page-title { font-size: 18px; font-weight: 700; color: var(--text); margin-bottom: 4px; }
.faq-page-sub   { font-size: 13px; color: var(--muted); margin-bottom: 22px; }

/* ── Search ───────────────────────────────────────────────── */
.faq-search-wrap {
  position: relative; max-width: 560px;
  margin-bottom: 24px;
}
.faq-search-wrap i {
  position: absolute; left: 14px; top: 50%;
  transform: translateY(-50%); color: var(--muted); font-size: 14px;
}
.faq-search {
  width: 100%; padding: 10px 14px 10px 38px;
  border: 1.5px solid var(--border); border-radius: 8px;
  font-family: var(--font); font-size: 13.5px; color: var(--text);
  outline: none; background: var(--white); transition: border-color .15s;
  box-sizing: border-box;
}
.faq-search:focus { border-color: var(--blue); }

/* ── Category tabs ────────────────────────────────────────── */
.faq-tabs {
  display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 22px;
}
.faq-tab {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600;
  cursor: pointer; border: 1.5px solid var(--border);
  background: var(--white); color: var(--muted);
  transition: all .15s; font-family: var(--font);
}
.faq-tab i { font-size: 13px; }
.faq-tab:hover  { border-color: var(--blue); color: var(--blue); background: #EFF6FF; }
.faq-tab.active { background: var(--blue); color: #fff; border-color: var(--blue); }

/* ── FAQ panels ───────────────────────────────────────────── */
.faq-panel { display: none; }
.faq-panel.active { display: block; }

/* ── FAQ accordion items ──────────────────────────────────── */
.faq-card {
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; margin-bottom: 10px; overflow: hidden;
}
.faq-card.faq-hidden { display: none; }

.faq-q {
  display: flex; align-items: center; justify-content: space-between;
  padding: 15px 18px; cursor: pointer;
  font-size: 14px; font-weight: 600; color: var(--text);
  transition: background .15s; user-select: none; gap: 12px;
}
.faq-q:hover { background: #F9FAFB; }
.faq-q-left { display: flex; align-items: center; gap: 12px; }
.faq-q-num {
  width: 26px; height: 26px; border-radius: 50%;
  background: var(--blue); color: #fff;
  display: flex; align-items: center; justify-content: center;
  font-size: 11px; font-weight: 700; flex-shrink: 0;
}
.faq-q-chevron {
  font-size: 11px; color: var(--muted);
  transition: transform .25s; flex-shrink: 0;
}
.faq-card.open .faq-q-chevron { transform: rotate(180deg); }
.faq-card.open .faq-q { background: #F9FAFB; }

.faq-a {
  display: none; padding: 0 18px 16px 56px;
  font-size: 13.5px; color: var(--muted); line-height: 1.8;
  border-top: 1px solid var(--border);
}
.faq-card.open .faq-a { display: block; padding-top: 14px; }

.faq-a ul { padding-left: 18px; margin: 8px 0; }
.faq-a ul li { margin-bottom: 4px; }
.faq-a strong { color: var(--text); }

/* ── Search result mode ───────────────────────────────────── */
.faq-search-results { display: none; }
.faq-search-results.active { display: block; }
.faq-no-results {
  text-align: center; padding: 48px 20px;
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; color: var(--muted); font-size: 14px;
}
.faq-no-results i { font-size: 36px; display: block; margin-bottom: 12px; color: var(--border); }

/* ── Stats bar ────────────────────────────────────────────── */
.faq-stats {
  display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 22px;
}
.faq-stat {
  flex: 1; min-width: 100px;
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; padding: 12px 16px; text-align: center;
}
.faq-stat-num   { font-size: 20px; font-weight: 700; color: var(--blue); }
.faq-stat-label { font-size: 11.5px; color: var(--muted); margin-top: 2px; }

/* ── CTA card ─────────────────────────────────────────────── */
.faq-cta {
  margin-top: 24px; padding: 20px 24px;
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; display: flex; align-items: center;
  justify-content: space-between; flex-wrap: wrap; gap: 14px;
}
.faq-cta-text  { font-size: 14px; font-weight: 600; color: var(--text); }
.faq-cta-sub   { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
.faq-cta-btn {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 9px 18px; background: var(--blue); color: #fff;
  border: none; border-radius: 8px; font-family: var(--font);
  font-size: 13px; font-weight: 700; cursor: pointer;
  text-decoration: none; transition: background .15s;
}
.faq-cta-btn:hover { background: #132B50; }

@media (max-width: 600px) {
  .faq-wrap { padding: 16px 14px 48px; }
  .faq-a { padding-left: 18px; }
  .faq-stats { flex-direction: column; }
}
</style>

<?php
// FAQ data structure
$faq_categories = [
  [
    'id'    => 'submission',
    'icon'  => 'fas fa-upload',
    'label' => 'Submission & Account',
    'faqs'  => [
      ['q' => 'How do I submit a new paper?',
       'a' => 'Log in to the Author Portal, click <strong>Submit New Manuscript</strong>, select the journal, upload your manuscript and required documents, then click Submit. A tracking code is generated instantly.'],
      ['q' => 'Can I submit more than one paper using the same account?',
       'a' => 'Yes. You can submit and manage multiple papers from a single author account without any restrictions.'],
      ['q' => 'Can I edit my paper after submission?',
       'a' => 'You cannot edit a submitted paper directly. However, if a revision is requested by the editorial team, you can upload a revised version through the portal.'],
      ['q' => 'How do I add or update co-authors?',
       'a' => 'Co-authors can be added during the submission process. After submission, author changes are only allowed with explicit editorial approval.'],
      ['q' => 'What file formats are accepted for manuscript submission?',
       'a' => 'We accept <strong>DOCX/DOC</strong> for the editable manuscript and <strong>PDF</strong> for the PDF version. Both are required for a complete submission.'],
    ]
  ],
  [
    'id'    => 'tracking',
    'icon'  => 'fas fa-search',
    'label' => 'Tracking & Review',
    'faqs'  => [
      ['q' => 'How can I track the status of my paper?',
       'a' => 'Go to <strong>Track Your Paper</strong> in the portal. You can view real-time status updates, reviewer progress, and editorial decisions at any time.'],
      ['q' => 'What do the paper status labels mean?',
       'a' => '<ul>
                 <li><strong>Submitted</strong> – Paper received and awaiting initial review</li>
                 <li><strong>Under Review</strong> – Being evaluated by reviewers</li>
                 <li><strong>Revision Required</strong> – Changes have been requested</li>
                 <li><strong>Accepted</strong> – Approved for publication</li>
                 <li><strong>Rejected</strong> – Not accepted for publication</li>
                 <li><strong>Published</strong> – Paper is live online with a DOI</li>
               </ul>'],
      ['q' => 'How long does the review process take?',
       'a' => 'The typical peer review turnaround is <strong>4–6 weeks</strong> from the date of submission. You will be notified by email at each stage.'],
      ['q' => 'Why has my paper been in "Under Review" for a long time?',
       'a' => 'Review timelines can vary depending on reviewer availability and manuscript complexity. If it has been more than 8 weeks, you can raise a support ticket to enquire about the status.'],
    ]
  ],
  [
    'id'    => 'revision',
    'icon'  => 'fas fa-edit',
    'label' => 'Revision & Decision',
    'faqs'  => [
      ['q' => 'How will I receive reviewer comments?',
       'a' => 'Reviewer and editor comments will be available in the <strong>Track Your Paper</strong> section and sent to your registered email.'],
      ['q' => 'How do I submit a revised manuscript?',
       'a' => 'In the Track Your Paper section, click <strong>View Comments</strong> to review feedback, then click <strong>Resubmit</strong> to upload your revised file along with a response letter addressing the reviewer comments.'],
      ['q' => 'What should I include with my revised submission?',
       'a' => 'You must include: (1) the revised manuscript file, and (2) a response letter clearly addressing each reviewer comment point-by-point.'],
      ['q' => 'What happens if my paper is rejected?',
       'a' => 'If your paper is rejected, you will receive a detailed reason. You may address the concerns and submit a new manuscript, or choose to submit to a different journal.'],
    ]
  ],
  [
    'id'    => 'fee',
    'icon'  => 'fas fa-dollar-sign',
    'label' => 'Publication Fee (APC)',
    'faqs'  => [
      ['q' => 'When do I need to pay the publication fee?',
       'a' => 'The Article Processing Charge (APC) is required <strong>only after your paper is accepted</strong>. There is no submission fee.'],
      ['q' => 'What payment methods are available?',
       'a' => 'We accept: <strong>Credit/Debit Cards</strong>, <strong>Net Banking</strong>, <strong>UPI</strong>, <strong>PayPal</strong>, <strong>Stripe</strong>, <strong>Razorpay</strong>, and <strong>Bank/Wire Transfer</strong>.'],
      ['q' => 'Can I get an invoice for payment?',
       'a' => 'Yes. You can download a Proforma Invoice before payment and a Tax Invoice &amp; Receipt after payment confirmation from the Author Portal.'],
      ['q' => 'Is the publication fee refundable?',
       'a' => 'Publication fees are <strong>non-refundable</strong> once payment is confirmed and processing has started. Please refer to our Refund Policy for full details.'],
      ['q' => 'Are there any waivers or discounts available?',
       'a' => 'Waivers may be available for authors from low-income countries or in special circumstances. Contact the editorial office to enquire about discount codes or waiver requests.'],
    ]
  ],
  [
    'id'    => 'publication',
    'icon'  => 'fas fa-certificate',
    'label' => 'Publication & DOI',
    'faqs'  => [
      ['q' => 'Will my paper receive a DOI?',
       'a' => 'Yes. All accepted and published papers are assigned a permanent Digital Object Identifier (DOI) via CrossRef, making your work globally citable.'],
      ['q' => 'How long after payment will my paper be published?',
       'a' => 'After payment confirmation and final document submission, papers are typically published within <strong>3–7 business days</strong>.'],
      ['q' => 'How can I download my acceptance or publication certificate?',
       'a' => 'Certificates are available under the <strong>Documents &amp; Certificates</strong> section of the Track Your Paper page in your Author Portal.'],
      ['q' => 'Will my paper be indexed in Google Scholar?',
       'a' => 'Yes. All published papers are submitted for indexing in Google Scholar, CrossRef, and other supported databases.'],
    ]
  ],
  [
    'id'    => 'process',
    'icon'  => 'fas fa-cogs',
    'label' => 'Post-Acceptance Steps',
    'faqs'  => [
      ['q' => 'What are the next steps after acceptance?',
       'a' => 'After your paper is accepted, follow these steps through the Author Portal:
               <ul>
                 <li>Download and review the <strong>Acceptance Letter</strong></li>
                 <li>Complete the <strong>Publication Fee (APC)</strong> payment</li>
                 <li>Upload the <strong>Copyright Transfer Form</strong></li>
                 <li>Upload the <strong>Final Manuscript</strong> (camera-ready version)</li>
                 <li>Editorial team verifies payment and documents</li>
                 <li>DOI is assigned and paper is published online</li>
                 <li>Download your <strong>Publication Certificate</strong></li>
               </ul>
               You will receive email notifications at each stage.'],
      ['q' => 'What is the Final Submission and when is it required?',
       'a' => 'The Final Submission is the camera-ready version of your accepted paper submitted along with the payment receipt, declaration form, and copyright transfer agreement.'],
    ]
  ],
  [
    'id'    => 'peer',
    'icon'  => 'fas fa-users',
    'label' => 'Peer Review Process',
    'faqs'  => [
      ['q' => 'How does the peer review process work?',
       'a' => 'CIJSS International follows a <strong>double-blind peer review</strong> process:
               <ul>
                 <li>Editorial team performs initial quality and scope check</li>
                 <li>Manuscripts passing this stage are sent to expert reviewers</li>
                 <li>Reviewers evaluate originality, methodology, relevance, and clarity</li>
                 <li>Reviewer identities remain confidential throughout</li>
                 <li>Based on reviewer feedback, the editor decides: Accept / Accept with Changes / Resubmit / Reject</li>
                 <li>All comments are shared transparently through the Author Portal</li>
               </ul>'],
      ['q' => 'How many reviewers will evaluate my paper?',
       'a' => 'Each manuscript is evaluated by a minimum of <strong>two independent expert reviewers</strong> in the relevant field.'],
      ['q' => 'Can I suggest reviewers for my paper?',
       'a' => 'Yes. During the submission process, you can suggest preferred reviewers. However, the final selection is at the discretion of the editorial team to avoid conflicts of interest.'],
    ]
  ],
  [
    'id'    => 'support',
    'icon'  => 'fas fa-headset',
    'label' => 'Profile & Support',
    'faqs'  => [
      ['q' => 'How do I update my profile information?',
       'a' => 'Go to <strong>Author Profile Management</strong> in the sidebar to update your affiliation, contact details, ORCID ID, or other profile information.'],
      ['q' => 'How do I change my password?',
       'a' => 'Click <strong>Change Password</strong> in the sidebar. You will need to enter your current password and then set a new one.'],
      ['q' => 'Is my data secure on the portal?',
       'a' => 'Yes. The portal uses secure HTTPS encryption and strict access controls to protect all author data and submitted manuscripts.'],
      ['q' => 'How do I raise a support ticket?',
       'a' => 'Click <strong>Raise a Ticket</strong> in the sidebar, fill in the subject and description of your issue, and submit. The editorial team will respond within 1–2 business days.'],
      ['q' => 'I forgot my password. What should I do?',
       'a' => 'Click <strong>Forgot Password</strong> on the login page and follow the reset instructions sent to your registered email address.'],
    ]
  ],
];

// Count total FAQs
$total_faqs = array_sum(array_map(fn($c) => count($c['faqs']), $faq_categories));
?>

<div class="faq-wrap">

  <!-- Header -->
  <div class="faq-page-title">Frequently Asked Questions</div>
  <div class="faq-page-sub">Everything you need to know about submitting and publishing your research</div>

  <!-- Stats -->
  <div class="faq-stats">
    <div class="faq-stat">
      <div class="faq-stat-num"><?= $total_faqs ?></div>
      <div class="faq-stat-label">Total FAQs</div>
    </div>
    <div class="faq-stat">
      <div class="faq-stat-num"><?= count($faq_categories) ?></div>
      <div class="faq-stat-label">Categories</div>
    </div>
    <div class="faq-stat">
      <div class="faq-stat-num">4–6 wk</div>
      <div class="faq-stat-label">Avg. Review Time</div>
    </div>
    <div class="faq-stat">
      <div class="faq-stat-num">24/7</div>
      <div class="faq-stat-label">Portal Access</div>
    </div>
  </div>

  <!-- Search -->
  <div class="faq-search-wrap">
    <i class="fas fa-search"></i>
    <input type="text" id="faqSearch" class="faq-search"
           placeholder="Search FAQs… e.g. payment, revision, DOI, submission">
  </div>

  <!-- Search results container -->
  <div class="faq-search-results" id="searchResults"></div>

  <!-- Tabs -->
  <div class="faq-tabs" id="faqTabNav">
    <?php foreach ($faq_categories as $i => $cat): ?>
    <button class="faq-tab <?= $i === 0 ? 'active' : '' ?>"
            onclick="faqTab(this,'panel-<?= $cat['id'] ?>')">
      <i class="<?= $cat['icon'] ?>"></i>
      <?= htmlspecialchars($cat['label']) ?>
    </button>
    <?php endforeach; ?>
  </div>

  <!-- Panels -->
  <?php foreach ($faq_categories as $ci => $cat):
    $qnum = 1;
    foreach ($faq_categories as $prev) {
      if ($prev['id'] === $cat['id']) break;
      $qnum += count($prev['faqs']);
    }
  ?>
  <div class="faq-panel <?= $ci === 0 ? 'active' : '' ?>"
       id="panel-<?= $cat['id'] ?>"
       data-category="<?= $cat['id'] ?>">

    <?php foreach ($cat['faqs'] as $fi => $faq): ?>
    <div class="faq-card"
         data-question="<?= htmlspecialchars(strtolower($faq['q'])) ?>"
         data-answer="<?= htmlspecialchars(strtolower(strip_tags($faq['a']))) ?>"
         data-category="<?= $cat['id'] ?>">
      <div class="faq-q" onclick="toggleFaq(this)">
        <div class="faq-q-left">
          <div class="faq-q-num"><?= $qnum + $fi ?></div>
          <?= htmlspecialchars($faq['q']) ?>
        </div>
        <i class="fas fa-chevron-down faq-q-chevron"></i>
      </div>
      <div class="faq-a"><?= $faq['a'] ?></div>
    </div>
    <?php endforeach; ?>

  </div>
  <?php endforeach; ?>

  <!-- CTA -->
  <div class="faq-cta">
    <div>
      <div class="faq-cta-text">Still have a question?</div>
      <div class="faq-cta-sub">Our support team is here to help — raise a ticket and we'll respond within 1–2 business days.</div>
    </div>
    <a href="tickets.php" class="faq-cta-btn">
      <i class="fas fa-ticket-alt"></i> Raise a Support Ticket
    </a>
  </div>

</div>

<script>
// Toggle accordion
function toggleFaq(el) {
  const card = el.closest('.faq-card');
  const isOpen = card.classList.contains('open');
  // Close all in same panel
  const panel = card.closest('.faq-panel, .faq-search-results');
  if (panel) panel.querySelectorAll('.faq-card.open').forEach(c => c.classList.remove('open'));
  if (!isOpen) card.classList.add('open');
}

// Switch tab
function faqTab(btn, panelId) {
  document.querySelectorAll('.faq-tab').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.faq-panel').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.getElementById(panelId).classList.add('active');
  // Hide search results if visible
  clearSearch();
}

// Search
const searchInput = document.getElementById('faqSearch');
const searchResults = document.getElementById('searchResults');
const tabNav = document.getElementById('faqTabNav');

searchInput.addEventListener('input', function() {
  const q = this.value.trim().toLowerCase();
  if (!q) { clearSearch(); return; }

  const all = document.querySelectorAll('.faq-panel .faq-card');
  const matches = [];
  all.forEach(card => {
    const question = card.dataset.question || '';
    const answer   = card.dataset.answer   || '';
    if (question.includes(q) || answer.includes(q)) matches.push(card);
  });

  // Hide panels & tabs, show search results area
  document.querySelectorAll('.faq-panel').forEach(p => p.classList.remove('active'));
  tabNav.style.opacity = '.4';
  tabNav.style.pointerEvents = 'none';

  searchResults.innerHTML = '';
  if (matches.length === 0) {
    searchResults.innerHTML = `<div class="faq-no-results"><i class="fas fa-search"></i>No FAQs found for "<strong>${q}</strong>". Try a different keyword.</div>`;
  } else {
    const info = document.createElement('div');
    info.style.cssText = 'font-size:12.5px;color:var(--muted);margin-bottom:12px;font-weight:600;';
    info.textContent = matches.length + ' result' + (matches.length > 1 ? 's' : '') + ' found';
    searchResults.appendChild(info);
    matches.forEach(card => {
      const clone = card.cloneNode(true);
      clone.classList.remove('open');
      clone.querySelector('.faq-q').addEventListener('click', function() { toggleFaq(this); });
      searchResults.appendChild(clone);
    });
  }
  searchResults.classList.add('active');
});

function clearSearch() {
  searchInput.value = '';
  searchResults.innerHTML = '';
  searchResults.classList.remove('active');
  tabNav.style.opacity = '';
  tabNav.style.pointerEvents = '';
  // Re-activate first panel if nothing is active
  if (!document.querySelector('.faq-panel.active')) {
    document.querySelector('.faq-panel')?.classList.add('active');
    document.querySelector('.faq-tab')?.classList.add('active');
  }
}

// Clear on Escape
document.addEventListener('keydown', e => { if (e.key === 'Escape') clearSearch(); });
</script>

<?php layoutEnd(); ?>