<?php
// Load footer configuration and site config FIRST
$footerConfigFile = __DIR__ . '/data/footer_config.json';
$footerData = [];
if (file_exists($footerConfigFile)) {
    $footerData = json_decode(file_get_contents($footerConfigFile), true) ?: [];
}

// Load site config for social media and footer color
$configFile = __DIR__ . '/data/site_config.json';
$siteConfig = ['footer_bg_color' => '#f5f5f5', 'social_media' => []];
if (file_exists($configFile)) {
    $config = json_decode(file_get_contents($configFile), true);
    if (is_array($config)) $siteConfig = array_merge($siteConfig, $config);
}
?>

<!-- Newsletter Banner - Above Footer -->
<?php include_once __DIR__ . '/components/newsletter_banner.php'; ?>

<footer class="site-footer" style="background:<?php echo htmlspecialchars($siteConfig['footer_bg_color'] ?? '#1a1a1a'); ?>; border-top:1px solid #333; padding:60px 16px 1px; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>;">

  <!-- Main Footer Grid: 4 Columns -->
  <div class="footer-container" style="max-width:1200px; margin:0 auto; display:grid; grid-template-columns:repeat(4, 1fr); gap:40px; margin-bottom:60px;">
    
    <!-- Column 1: Contact Info -->
    <?php if (!empty($footerData['columns']['contact'])): ?>
    <div class="footer-column">
      <h3 style="margin:0 0 20px 0; font-size:16px; font-weight:600; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>;">
        <?php echo htmlspecialchars($footerData['columns']['contact']['title'] ?? 'Contact Info'); ?>
      </h3>
      <ul style="list-style:none; padding:0; margin:0;">
        <?php foreach ($footerData['columns']['contact']['items'] as $item): ?>
        <li style="margin-bottom:16px;">
          <p style="margin:0; font-size:11px; color:#ccc; font-weight:500; text-transform:capitalize;">
            <?php echo htmlspecialchars($item['label']); ?>:
          </p>
          <p style="margin:6px 0 0; font-size:14px; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>; line-height:1.5;">
            <?php echo htmlspecialchars($item['value']); ?>
          </p>
        </li>
        <?php endforeach; ?>
      </ul>
    </div>
    <?php endif; ?>

    <!-- Column 2: Our Stores -->
    <?php if (!empty($footerData['columns']['stores'])): ?>
    <div class="footer-column">
      <h3 style="margin:0 0 20px 0; font-size:16px; font-weight:600; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>;">
        <?php echo htmlspecialchars($footerData['columns']['stores']['title'] ?? 'Our Stores'); ?>
      </h3>
      <ul style="list-style:none; padding:0; margin:0;">
        <?php foreach ($footerData['columns']['stores']['items'] as $item): ?>
        <li style="margin-bottom:12px;">
          <p style="margin:0; font-size:14px; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>; line-height:1.5;">
            <?php echo htmlspecialchars($item['label']); ?>
          </p>
        </li>
        <?php endforeach; ?>
      </ul>
    </div>
    <?php endif; ?>

    <!-- Column 3: Useful Links -->
    <?php if (!empty($footerData['columns']['links'])): ?>
    <div class="footer-column">
      <h3 style="margin:0 0 20px 0; font-size:16px; font-weight:600; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>;">
        <?php echo htmlspecialchars($footerData['columns']['links']['title'] ?? 'Useful Links'); ?>
      </h3>
      <ul style="list-style:none; padding:0; margin:0;">
        <?php foreach ($footerData['columns']['links']['items'] as $link): ?>
        <li style="margin-bottom:12px;">
          <a href="<?php echo htmlspecialchars($link['url']); ?>" style="color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>; text-decoration:none; font-size:14px; transition:color 0.3s ease;">
            <?php echo htmlspecialchars($link['label']); ?>
          </a>
        </li>
        <?php endforeach; ?>
      </ul>
    </div>
    <?php endif; ?>

    <!-- Column 4: Newsletter -->
    <?php if (!empty($footerData['columns']['newsletter'])): ?>
    <div class="footer-column">
      <h3 style="margin:0 0 20px 0; font-size:16px; font-weight:600; color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>;">
        <?php echo htmlspecialchars($footerData['columns']['newsletter']['title'] ?? 'Join Our Newsletter'); ?>
      </h3>
      <p style="margin:0 0 15px 0; font-size:13px; color:#ccc; line-height:1.5;">
        <?php echo htmlspecialchars($footerData['columns']['newsletter']['description'] ?? 'Will be used in accordance with our privacy policy'); ?>
      </p>
      <form style="display:flex; gap:0; margin-bottom:20px;">
        <input type="email" placeholder="Your email address" style="flex:1; padding:12px 14px; border:1px solid #444; border-radius:0; font-size:13px; background:#2a2a2a; color:#fff;" required>
        <button type="submit" style="background:#F07E2D; color:#fff; border:none; padding:12px 20px; border-radius:0; font-weight:600; cursor:pointer; font-size:13px; transition:background 0.3s ease;">
          <span style="font-size:16px;">→</span>
        </button>
      </form>
      <!-- Social Media Icons Below Newsletter -->
      <div style="display:flex; gap:16px; align-items:center; justify-content:center;">
        <?php if (!empty($siteConfig['social_media']) && is_array($siteConfig['social_media'])): ?>
          <?php foreach ($siteConfig['social_media'] as $social): ?>
          <a href="<?php echo htmlspecialchars($social['link']); ?>" target="_blank" rel="noopener" style="color:<?php echo htmlspecialchars($siteConfig['footer_text_color'] ?? '#ffffff'); ?>; text-decoration:none; font-size:18px; transition:color 0.3s ease; display:flex; align-items:center; justify-content:center;" title="<?php echo htmlspecialchars($social['name']); ?>">
            <?php 
              // Map platform to Font Awesome brand icon
              $platform = strtolower($social['platform'] ?? '');
              $faIcons = [
                'instagram' => '<i class="fab fa-instagram" style="font-size:20px;"></i>',
                'facebook' => '<i class="fab fa-facebook" style="font-size:20px;"></i>',
                'twitter' => '<i class="fab fa-twitter" style="font-size:20px;"></i>',
                'twiter' => '<i class="fab fa-twitter" style="font-size:20px;"></i>',
                'thread' => '<i class="fab fa-threads" style="font-size:20px;"></i>',
                'threads' => '<i class="fab fa-threads" style="font-size:20px;"></i>',
                'linkedin' => '<i class="fab fa-linkedin" style="font-size:20px;"></i>',
                'youtube' => '<i class="fab fa-youtube" style="font-size:20px;"></i>',
                'tiktok' => '<i class="fab fa-tiktok" style="font-size:20px;"></i>',
                'pinterest' => '<i class="fab fa-pinterest" style="font-size:20px;"></i>',
                'snapchat' => '<i class="fab fa-snapchat" style="font-size:20px;"></i>',
                'whatsapp' => '<i class="fab fa-whatsapp" style="font-size:20px;"></i>',
                'telegram' => '<i class="fab fa-telegram" style="font-size:20px;"></i>'
              ];
              echo $faIcons[$platform] ?? '<i class="fas fa-link" style="font-size:20px;"></i>';
            ?>
          </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

  </div>

  <!-- Payment Methods & Copyright Section -->
  <div style="border-top:1px solid #333; border-bottom:1px solid #333; padding:30px 0;">
    <div style="max-width:1200px; margin:0 auto; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:20px;">
      <!-- Left: Payment Methods (Visa, Mastercard, AMEX) -->
      <div style="display:flex; gap:12px; align-items:center;">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='25' viewBox='0 0 40 25'%3E%3Crect width='40' height='25' fill='%231434CB' rx='2'/%3E%3Ctext x='50%25' y='50%25' font-size='8' fill='white' text-anchor='middle' dominant-baseline='middle' font-weight='bold'%3EVISA%3C/text%3E%3C/svg%3E" alt="Visa" style="height:25px;">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='25' viewBox='0 0 40 25'%3E%3Ccircle cx='15' cy='12.5' r='8' fill='%23EB001B'/%3E%3Ccircle cx='25' cy='12.5' r='8' fill='%23F79E1B'/%3E%3C/svg%3E" alt="Mastercard" style="height:25px;">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='25' viewBox='0 0 40 25'%3E%3Crect width='40' height='25' fill='%23006FCF' rx='2'/%3E%3Ctext x='50%25' y='50%25' font-size='7' fill='white' text-anchor='middle' dominant-baseline='middle' font-weight='bold'%3EAMEX%3C/text%3E%3C/svg%3E" alt="Amex" style="height:25px;">
      </div>
      <!-- Center: Copyright -->
      <p style="margin:0; font-size:12px; color:#ccc; text-align:center; flex:1;">
        © <?php echo date('Y'); ?> Emporio Sport. All Rights Reserved
      </p>
      <!-- Right: App Store Buttons -->
      <div style="display:flex; gap:12px; align-items:center;">
        <a href="https://apps.apple.com" target="_blank" rel="noopener" style="display:inline-block; text-decoration:none;">
          <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='40' viewBox='0 0 120 40'%3E%3Crect width='120' height='40' fill='%23000' rx='4'/%3E%3Ctext x='60' y='20' font-size='10' fill='white' text-anchor='middle' dominant-baseline='middle' font-weight='bold'%3EApp Store%3C/text%3E%3C/svg%3E" alt="App Store" style="height:35px;">
        </a>
        <a href="https://play.google.com" target="_blank" rel="noopener" style="display:inline-block; text-decoration:none;">
          <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='40' viewBox='0 0 120 40'%3E%3Crect width='120' height='40' fill='%23000' rx='4'/%3E%3Ctext x='60' y='20' font-size='10' fill='white' text-anchor='middle' dominant-baseline='middle' font-weight='bold'%3EGoogle Play%3C/text%3E%3C/svg%3E" alt="Google Play" style="height:35px;">
        </a>
      </div>
    </div>
  </div>

</footer>

<!-- Auth Modals -->
<div id="loginModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
  <div class="modal-content" style="max-width:420px; background:#fff; padding:24px; border-radius:8px;">
    <span class="modal-close" onclick="closeLoginModal()" style="float:right; font-size:28px; cursor:pointer;">&times;</span>
    <h2>Sign In</h2>
    <form id="loginForm" style="display:flex;flex-direction:column;gap:10px; margin-top:14px;">
      <input type="text" id="loginName" placeholder="Username" autocomplete="username" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <input type="password" id="loginPass" placeholder="Password" autocomplete="current-password" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <button class="btn" type="submit">Sign In</button>
    </form>
    <div id="loginMsg" style="margin-top:10px; text-align:center; color:#b00; font-weight:600; display:none;"></div>
    <p style="margin-top:8px; text-align:center;">
      <a href="#" onclick="openForgotModal(); return false;">Forgot password?</a>
      &nbsp;·&nbsp;
      <span class="muted">Don't have an account? <a href="#" onclick="showSignupType(); return false;">Sign Up</a></span>
    </p>
  </div>
</div>

<!-- Forgot Password Modal -->
<div id="forgotModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
  <div class="modal-content" style="max-width:480px; background:#fff; padding:20px; border-radius:8px;">
    <span class="modal-close" onclick="closeForgotModal()" style="float:right; font-size:28px; cursor:pointer;">&times;</span>
    <h2>Reset Password</h2>
    <p class="muted">Enter the email address associated with your account. We'll generate a reset link for local development below.</p>
    <form id="forgotForm" style="display:flex; flex-direction:column; gap:10px; margin-top:12px;">
      <input type="email" id="forgotEmail" placeholder="you@example.com" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <button class="btn" type="submit">Send Reset Link</button>
    </form>
    <div id="forgotMsg" style="margin-top:10px; text-align:left; display:none;"></div>
  </div>
</div>

<div id="signupTypeModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
  <div class="modal-content" style="max-width:420px; background:#fff; padding:24px; border-radius:8px;">
    <span class="modal-close" onclick="closeSignupTypeModal()" style="float:right; font-size:28px; cursor:pointer;">&times;</span>
    <h2>Sign Up As</h2>
    <p class="muted" style="margin-bottom:14px;">Choose your account type:</p>
    <button class="btn" type="button" onclick="showSignupForm('user')" style="width:100%; margin-bottom:8px;">User</button>
    <!-- Admin signup removed: admins must be promoted from the database by an existing admin -->
  </div>
</div>

<div id="signupModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
  <div class="modal-content" style="max-width:500px; background:#fff; padding:24px; border-radius:8px; max-height:90vh; overflow-y:auto;">
    <span class="modal-close" onclick="closeSignupModal()" style="float:right; font-size:28px; cursor:pointer;">&times;</span>
    <h2>Sign Up</h2>
    <form id="signupForm" style="display:flex;flex-direction:column;gap:8px; margin-top:14px;">
      <input type="hidden" id="signupUserType" value="user">
      <input type="text" id="signupName" placeholder="Full Name" autocomplete="name" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <input type="email" id="signupEmail" placeholder="Email" autocomplete="email" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <input type="tel" id="signupPhone" placeholder="Phone" autocomplete="tel" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <select id="signupGender" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
        <option value="">Select Gender</option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
        <option value="Other">Other</option>
      </select>
      <input type="number" id="signupAge" placeholder="Age" required min="18" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <input type="password" id="signupPass" placeholder="Password (min 8 chars, letter, number, special char)" autocomplete="new-password" required style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
      <button class="btn" type="submit">Create Account</button>
    </form>
    <div id="signupMsg" style="margin-top:10px; text-align:center; color:#b00; font-weight:600; display:none;"></div>
  </div>
</div>

<script>
function openLoginModal() {
  document.getElementById('loginModal').style.display = 'flex';
}
function closeLoginModal() {
  document.getElementById('loginModal').style.display = 'none';
}
function showSignupType() {
  // Open signup directly as regular user (admin signup removed)
  closeLoginModal();
  document.getElementById('signupUserType').value = 'user';
  document.getElementById('signupModal').style.display = 'flex';
}
function closeSignupTypeModal() {
  document.getElementById('signupTypeModal').style.display = 'none';
}
function showSignupForm(type) {
  // Always treat signups as regular users; ignore any provided type
  document.getElementById('signupUserType').value = 'user';
  closeSignupTypeModal();
  document.getElementById('signupModal').style.display = 'flex';
}
function closeSignupModal() {
  document.getElementById('signupModal').style.display = 'none';
}

// Login form submission
document.getElementById('loginForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const name = document.getElementById('loginName').value;
  const password = document.getElementById('loginPass').value;
  const formData = new FormData();
  formData.append('name', name);
  formData.append('password', password);
  
  try {
    const res = await fetch('api_login.php', { method: 'POST', body: formData });
    const data = await res.json();
    
    const showLoginMessage = (msg, color) => {
      const el = document.getElementById('loginMsg');
      el.style.display = 'block';
      el.style.color = color || '#b00';
      el.textContent = msg;
    };

    if (data.success) {
      window.location.href = data.redirect;
    } else if (data.message === 'not_found') {
      showLoginMessage('User not found. Please sign up.', '#b00');
      setTimeout(() => showSignupType(), 800);
    } else if (data.message === 'wrong_password') {
      showLoginMessage('Incorrect password. Please try again.', '#b00');
    } else {
      showLoginMessage('Error: ' + (data.message || 'Unknown error'), '#b00');
    }
  } catch (err) {
    const el = document.getElementById('loginMsg'); el.style.display = 'block'; el.style.color = '#b00'; el.textContent = 'Network error. Please try again.';
  }
});

// Forgot password modal handlers
function openForgotModal() {
  closeLoginModal();
  document.getElementById('forgotModal').style.display = 'flex';
}
function closeForgotModal() {
  document.getElementById('forgotModal').style.display = 'none';
}

// Forgot password form submission
document.getElementById('forgotForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const email = document.getElementById('forgotEmail').value;
  const form = new FormData();
  form.append('email', email);
  const el = document.getElementById('forgotMsg');
  el.style.display = 'none';
  try {
    const res = await fetch('api_forgot_password.php', { method: 'POST', body: form });
    const data = await res.json();
    el.style.display = 'block';
    el.style.color = data.success ? '#080' : '#b00';
    if (data.success) {
      // Show a clear success message and do NOT expose any reset link in the UI
      el.innerHTML = '<strong>Password reset email has been sent successfully.</strong>';
    } else {
      // When the API returns an explicit not-found message show it; otherwise show a sensible default
      el.textContent = data.message || 'No account is registered with this email. Please sign up.';
    }
  } catch (err) {
    el.style.display = 'block'; el.style.color = '#b00'; el.textContent = 'Network error. Please try again.';
  }
});


// Signup form submission
document.getElementById('signupForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const name = document.getElementById('signupName').value;
  const email = document.getElementById('signupEmail').value;
  const phone = document.getElementById('signupPhone').value;
  const gender = document.getElementById('signupGender').value;
  const age = document.getElementById('signupAge').value;
  const password = document.getElementById('signupPass').value;
  const user_type = document.getElementById('signupUserType').value;
  
  const formData = new FormData();
  formData.append('name', name);
  formData.append('email', email);
  formData.append('phone', phone);
  formData.append('gender', gender);
  formData.append('age', age);
  formData.append('password', password);
  formData.append('user_type', user_type);
  
  try {
    const res = await fetch('api_signup.php', { method: 'POST', body: formData });
    const data = await res.json();
    const showSignupMessage = (msg, color) => {
      const el = document.getElementById('signupMsg');
      el.style.display = 'block';
      el.style.color = color || '#b00';
      el.textContent = msg;
    };

    if (data.success) {
      showSignupMessage('Account created. Redirecting to Sign In...', '#080');
      // close signup modal and open login modal after short delay
      setTimeout(() => {
        closeSignupModal();
        openLoginModal();
        // prefill login name with email or username
        const loginNameEl = document.getElementById('loginName');
        if (loginNameEl) loginNameEl.value = document.getElementById('signupEmail').value || document.getElementById('signupName').value || '';
        // clear signup message after opening login
        document.getElementById('signupMsg').style.display = 'none';
      }, 900);
    } else if (data.message === 'conflict') {
      // create friendly single-line conflict message
      const conflicts = data.conflicts || [];
      let msg = 'Already exists: ' + conflicts.join(', ');
      if (conflicts.length === 1 && conflicts[0] === 'name') msg = 'This username is already taken. Please choose another.';
      if (conflicts.length === 1 && conflicts[0] === 'email') msg = 'This email is already registered. Use another email or Sign In.';
      if (conflicts.length === 1 && conflicts[0] === 'phone') msg = 'This phone number is already used. Use another.';
      showSignupMessage(msg, '#b00');
    } else {
      showSignupMessage('Error: ' + (data.message || 'Unknown error'), '#b00');
    }
  } catch (err) {
    const el = document.getElementById('signupMsg'); el.style.display = 'block'; el.style.color = '#b00'; el.textContent = 'Network error. Please try again.';
  }
});

// Close modals when clicking outside
window.onclick = function(event) {
  const loginModal = document.getElementById('loginModal');
  const signupModal = document.getElementById('signupModal');
  const signupTypeModal = document.getElementById('signupTypeModal');
  
  if (event.target === loginModal) loginModal.style.display = 'none';
  if (event.target === signupModal) signupModal.style.display = 'none';
  if (event.target === signupTypeModal) signupTypeModal.style.display = 'none';
}

// User dropdown toggle / close handlers
function toggleUserDropdown(e) {
  e.stopPropagation();
  const d = document.getElementById('userDropdown');
  if (!d) return;
  d.style.display = (d.style.display === 'block') ? 'none' : 'block';
}

// Close user dropdown on outside click
document.addEventListener('click', function(ev) {
  const d = document.getElementById('userDropdown');
  if (!d) return;
  const navUser = document.getElementById('navUser');
  if (!navUser) return;
  if (!navUser.contains(ev.target)) {
    d.style.display = 'none';
  }
});

// Back to Top Button
const backToTopBtn = document.getElementById('backToTopBtn') || (() => {
  const btn = document.createElement('button');
  btn.id = 'backToTopBtn';
  btn.innerHTML = '↑';
  btn.title = 'Back to Top';
  btn.onclick = () => window.scrollTo({top: 0, behavior: 'smooth'});
  document.body.appendChild(btn);
  return btn;
})();

window.addEventListener('scroll', () => {
  if (window.pageYOffset > 300) {
    backToTopBtn.classList.add('show');
  } else {
    backToTopBtn.classList.remove('show');
  }
});
</script>

<!-- Back to Top Button -->
<button id="backToTopBtn" title="Back to Top">↑</button>
