import pool from '../config/db.js';

let tableChecked = false;

const defaultSettings = {
  stats_banner: {
    stat1_value: "10,000+",
    stat1_label: "Businesses",
    stat2_value: "50,000+",
    stat2_label: "Reviews",
    stat3_value: "100+",
    stat3_label: "Cities"
  },
  featured_businesses: {
    title: "Featured Halal Businesses",
    subtitle: "Verified top quality businesses in the network.",
    selected_ids: []
  },
  promo_popup: {
    title: "Reach thousands of local customers in the halal community.",
    headline: "Enterprise IT Infrastructure & Cybersecurity, Managed 24/7.",
    button_text: "Add Your Promotion Here",
    images: []
  }
};

const defaultPages = {
  "terms-of-service": {
    slug: "terms-of-service",
    title: "Terms of Service",
    subtitle: "Governing access, merchant listings, customer reviews, and general platform obligations.",
    last_updated: "September 2026",
    content: `### 1. Acceptance of Terms
By accessing or using KHUJOUSA ("the Platform"), you agree to be bound by these Terms of Service. If you disagree with any part of these terms, you may not access or use our directory services.

### 2. User Accounts & Responsibilities
Registered business owners, moderators, and consumers are responsible for safeguarding their login credentials and all activities occurring under their accounts. You agree to provide accurate, current, and complete registration information.

### 3. Merchant Listings & Accreditations
Business owners must represent their offerings truthfully. Any claims regarding Halal certification, Muslim ownership, or cuisine disclosures must be verifiable. KHUJOUSA reserves the right to audit, reject, or remove any listing that provides misleading information.

### 4. Consumer Reviews & Ratings Policy
Reviews must reflect authentic first-hand consumer experiences. KHUJOUSA strictly prohibits defamatory content, fake testimonials, commercial solicitation, and hate speech.

### 5. Intellectual Property
All trademarks, logos, service marks, and proprietary content displayed on KHUJOUSA are the property of KHUJOUSA or their respective merchant owners.

### 6. Disclaimers & Limitation of Liability
KHUJOUSA provides the directory on an "as is" and "as available" basis without warranties of any kind. We do not independently guarantee the religious accreditation of every individual dish or third-party service provider.

### 7. Modifications to Service
We reserve the right to modify or discontinue any part of our platform at any time with or without prior notice.`
  },
  "terms-of-usage": {
    slug: "terms-of-usage",
    title: "Terms of Usage & Acceptable Use Policy",
    subtitle: "Standards of conduct, acceptable use, and community safety guidelines across KHUJOUSA.",
    last_updated: "September 2026",
    content: `### 1. Scope & Purpose
This Acceptable Use Policy defines the standards of conduct expected from all visitors, registered members, and merchants interacting with the KHUJOUSA network.

### 2. Permitted Use
The Platform is intended for discovering halal-certified businesses, Muslim-owned services, submitting verified consumer feedback, and community engagement.

### 3. Prohibited Activities
When using KHUJOUSA, you agree NOT to:
- Scrape, harvest, or extract data from our directory using automated bots, crawlers, or spider tools.
- Post unlawful, harassing, obscene, fraudulent, or defamatory content.
- Impersonate another business owner, moderator, administrator, or customer.
- Attempt to gain unauthorized access to backend systems, database records, or accounts.
- Distribute malicious code, viruses, or disruptive scripts.

### 4. Content Standards & Anti-Spam
Merchants may not submit duplicate listings for identical locations or spam directory categories with unrelated keywords.

### 5. Enforcement & Penalties
KHUJOUSA moderators actively enforce these standards. Violations may result in formal warnings, listing suspension, or permanent account ban without liability.`
  },
  "privacy-notice": {
    slug: "privacy-notice",
    title: "Privacy Notice",
    subtitle: "How KHUJOUSA collects, safeguards, and handles your personal and business information.",
    last_updated: "September 2026",
    content: `### 1. Information We Collect
We collect information you provide directly, including:
- **Account Information**: Name, email address, phone number, and password credentials.
- **Merchant Details**: Business name, physical address, business hours, photos, accreditation documents, and tax filings.
- **Usage Data**: Search keywords, browser type, device details, and geographic location when using map features.

### 2. How We Use Your Information
We use your information to:
- Authenticate user accounts and maintain directory accuracy.
- Process and display public business listings.
- Communicate administrative notices, review verifications, and audit alerts.
- Monitor traffic analytics and improve overall directory performance.

### 3. Information Sharing & Third Parties
We do not sell personal visitor data. Information is only shared with:
- Public directory visitors (public business contact details only).
- Infrastructure providers (cloud databases, mapping geocoders).
- Legal authorities when required by applicable law or subpoena.

### 4. Cookies & Security
We use modern encryption standards (SSL/TLS, hashed passwords) and session storage to maintain secure authentication and preferences.

### 5. Your Rights & Choices
You may request access to, correction of, or deletion of your personal account data at any time by contacting our privacy officer.`
  },
  "about-us": {
    slug: "about-us",
    title: "About KHUJOUSA",
    subtitle: "Your Trusted Local Guide for Everything Halal Across the United States.",
    last_updated: "September 2026",
    mission: "To empower halal-conscious consumers and local businesses by creating the nation's most comprehensive, trusted, and verified halal directory.",
    vision: "Connecting millions of community members with authentic halal dining, ethical retail, healthcare, lodging, and professional services.",
    story: "KHUJOUSA began with a simple yet critical realization: finding authentic halal options, verified Muslim-owned businesses, and family-friendly services across American cities should be seamless, transparent, and trustworthy. We built this platform from the ground up to give entrepreneurs a powerful spotlight to thrive and customers a directory they can rely on with total peace of mind.",
    values: [
      {
        title: "Authenticity & Trust",
        description: "Rigorous verification of halal claims and transparent community disclosures ensure peace of mind for every family."
      },
      {
        title: "Community Empowerment",
        description: "Supporting independent entrepreneurs, artisans, and family-owned Muslim enterprises to achieve sustainable growth."
      },
      {
        title: "Quality & Excellence",
        description: "Curating verified user reviews, accurate geocoded map locations, and up-to-date operating hours."
      }
    ]
  },
  "contact-us": {
    slug: "contact-us",
    title: "Contact Us",
    subtitle: "We are here to help. Reach out to our community support and partnerships team.",
    support_email: "support@khujousa.com",
    phone: "(800) 555-KHUJO (5485)",
    address: "100 N Michigan Avenue, Suite 1400, Chicago, IL 60601",
    hours: "Monday - Friday: 9:00 AM - 6:00 PM CST",
    intro: "Have questions about listing your business, finding halal services in your city, or reporting an issue? Send us a message and our team will respond within 24 hours."
  }
};

async function ensureSettingsTable() {
  if (tableChecked) return;
  try {
    // 1. Site settings table
    await pool.query(`
      CREATE TABLE IF NOT EXISTS site_settings (
        setting_key VARCHAR(100) PRIMARY KEY,
        setting_value JSON NOT NULL,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB;
    `);

    // 2. Contact Inquiries table
    await pool.query(`
      CREATE TABLE IF NOT EXISTS contact_inquiries (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(150) NOT NULL,
        phone VARCHAR(50) NULL,
        email VARCHAR(150) NULL,
        subject VARCHAR(200) NULL,
        message TEXT NOT NULL,
        status VARCHAR(50) DEFAULT 'unread',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_ci_status (status),
        INDEX idx_ci_created (created_at)
      ) ENGINE=InnoDB;
    `);

    await pool.query(`ALTER TABLE contact_inquiries ADD COLUMN phone VARCHAR(50) NULL`).catch(() => {});
    await pool.query(`ALTER TABLE contact_inquiries MODIFY COLUMN email VARCHAR(150) NULL`).catch(() => {});

    tableChecked = true;
  } catch (err) {
    console.error("ensureSettingsTable error:", err.message);
  }
}

// GET /api/settings/public - Retrieve public-facing CMS and feature settings
export async function getPublicSettings(req, res) {
  try {
    await ensureSettingsTable();

    const [rows] = await pool.query(
      `SELECT setting_value FROM site_settings WHERE setting_key = 'public_features'`
    );

    if (rows.length === 0) {
      return res.json({
        success: true,
        settings: defaultSettings
      });
    }

    let parsed = rows[0].setting_value;
    if (typeof parsed === 'string') {
      try {
        parsed = JSON.parse(parsed);
      } catch (e) {
        parsed = defaultSettings;
      }
    }

    const merged = {
      stats_banner: { ...defaultSettings.stats_banner, ...(parsed.stats_banner || {}) },
      featured_businesses: { ...defaultSettings.featured_businesses, ...(parsed.featured_businesses || {}) },
      promo_popup: { ...defaultSettings.promo_popup, ...(parsed.promo_popup || {}) }
    };

    return res.json({
      success: true,
      settings: merged
    });
  } catch (err) {
    console.error("getPublicSettings error:", err);
    return res.json({
      success: true,
      settings: defaultSettings
    });
  }
}

// PUT /api/settings/public - Update public-facing CMS and feature settings (Admin/Moderator only)
export async function updatePublicSettings(req, res) {
  try {
    await ensureSettingsTable();

    if (!req.user || !['admin', 'moderator', 'super_admin'].includes(req.user.role)) {
      return res.status(403).json({ error: "Access denied. Administrative role required." });
    }

    const { stats_banner, featured_businesses, promo_popup } = req.body;

    const [existingRows] = await pool.query(
      `SELECT setting_value FROM site_settings WHERE setting_key = 'public_features'`
    );

    let current = defaultSettings;
    if (existingRows.length > 0) {
      try {
        current = typeof existingRows[0].setting_value === 'string'
          ? JSON.parse(existingRows[0].setting_value)
          : existingRows[0].setting_value;
      } catch (e) {}
    }

    const updated = {
      stats_banner: stats_banner ? { ...current.stats_banner, ...stats_banner } : current.stats_banner,
      featured_businesses: featured_businesses ? { ...current.featured_businesses, ...featured_businesses } : current.featured_businesses,
      promo_popup: promo_popup ? { ...current.promo_popup, ...promo_popup } : current.promo_popup
    };

    await pool.query(
      `INSERT INTO site_settings (setting_key, setting_value)
       VALUES ('public_features', ?)
       ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP`,
      [JSON.stringify(updated)]
    );

    if (promo_popup) {
      try {
        const [promoRows] = await pool.query(`SELECT id FROM promotions ORDER BY id ASC LIMIT 1`);
        const primaryImg = promo_popup.images && promo_popup.images.length > 0
          ? promo_popup.images[0]
          : "";
        const imagesJson = JSON.stringify(promo_popup.images || [primaryImg]);

        if (promoRows.length > 0) {
          await pool.query(
            `UPDATE promotions 
             SET title = ?, headline = ?, image_url = ?, images = ?, button_text = ?, button_url = ?
             WHERE id = ?`,
            [
              promo_popup.title || current.promo_popup.title,
              promo_popup.headline || "",
              primaryImg,
              imagesJson,
              promo_popup.button_text || current.promo_popup.button_text,
              '#/add-listing',
              promoRows[0].id
            ]
          );
        }
      } catch (syncErr) {
        console.warn("Could not sync with promotions table:", syncErr.message);
      }
    }

    return res.json({
      success: true,
      message: "Page settings updated successfully.",
      settings: updated
    });
  } catch (err) {
    console.error("updatePublicSettings error:", err);
    return res.status(500).json({ error: "Failed to update page settings." });
  }
}

// =========================================================================
// CMS PAGES CONTROLLERS (Terms of Service, Terms of Usage, Privacy, About Us, Contact Us)
// =========================================================================

// GET /api/settings/pages - Retrieve all CMS pages
export async function getAllPages(req, res) {
  try {
    await ensureSettingsTable();

    const [rows] = await pool.query(
      `SELECT setting_key, setting_value FROM site_settings WHERE setting_key LIKE 'page_%'`
    );

    const pages = {};
    for (const r of rows) {
      const slug = r.setting_key.replace(/^page_/, '').replace(/_/g, '-');
      let data = r.setting_value;
      if (typeof data === 'string') {
        try { data = JSON.parse(data); } catch (e) {}
      }
      pages[slug] = data;
    }

    // Ensure defaults exist in return map
    for (const [slug, def] of Object.entries(defaultPages)) {
      if (!pages[slug]) pages[slug] = def;
    }

    return res.json({ success: true, pages });
  } catch (err) {
    console.error("getAllPages error:", err);
    return res.status(500).json({ error: "Failed to retrieve CMS pages." });
  }
}

// GET /api/settings/pages/:slug - Retrieve single CMS page
export async function getPageBySlug(req, res) {
  try {
    await ensureSettingsTable();
    const slug = req.params.slug;
    const key = `page_${slug.replace(/-/g, '_')}`;

    const [rows] = await pool.query(
      `SELECT setting_value FROM site_settings WHERE setting_key = ?`,
      [key]
    );

    if (rows.length === 0) {
      if (defaultPages[slug]) {
        return res.json({ success: true, page: defaultPages[slug] });
      }
      return res.status(404).json({ error: "Page not found." });
    }

    let pageData = rows[0].setting_value;
    if (typeof pageData === 'string') {
      try { pageData = JSON.parse(pageData); } catch (e) {}
    }

    return res.json({ success: true, page: pageData });
  } catch (err) {
    console.error("getPageBySlug error:", err);
    return res.status(500).json({ error: "Failed to retrieve page content." });
  }
}

// PUT /api/settings/pages/:slug - Update single CMS page (Admin only)
export async function updatePageBySlug(req, res) {
  try {
    await ensureSettingsTable();

    if (!req.user || !['admin', 'moderator', 'super_admin'].includes(req.user.role)) {
      return res.status(403).json({ error: "Access denied. Administrative role required." });
    }

    const slug = req.params.slug;
    const key = `page_${slug.replace(/-/g, '_')}`;
    const pageData = req.body;

    if (!pageData) {
      return res.status(400).json({ error: "No page data provided." });
    }

    // Preserve slug in payload
    pageData.slug = slug;

    await pool.query(
      `INSERT INTO site_settings (setting_key, setting_value)
       VALUES (?, ?)
       ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP`,
      [key, JSON.stringify(pageData)]
    );

    return res.json({
      success: true,
      message: `Page '${slug}' updated successfully.`,
      page: pageData
    });
  } catch (err) {
    console.error("updatePageBySlug error:", err);
    return res.status(500).json({ error: "Failed to update page content." });
  }
}

// =========================================================================
// CONTACT INQUIRIES CONTROLLERS
// =========================================================================

// POST /api/settings/contact-inquiries - Public submission
export async function submitContactInquiry(req, res) {
  try {
    await ensureSettingsTable();
    const { name, phone, email, subject, message } = req.body;

    if (!name || !phone || !message) {
      return res.status(400).json({ error: "Please fill in your name, phone number, and message." });
    }

    const [result] = await pool.query(
      `INSERT INTO contact_inquiries (name, phone, email, subject, message, status)
       VALUES (?, ?, ?, ?, ?, 'unread')`,
      [name.trim(), phone.trim(), (email || '').trim() || null, (subject || '').trim(), message.trim()]
    );

    return res.status(201).json({
      success: true,
      message: "Thank you for contacting KHUJOUSA. Your inquiry has been received and our team will get back to you shortly.",
      inquiryId: result.insertId
    });
  } catch (err) {
    console.error("submitContactInquiry error:", err);
    return res.status(500).json({ error: "Failed to submit inquiry. Please try again." });
  }
}

// GET /api/settings/contact-inquiries - Admin retrieval
export async function getContactInquiries(req, res) {
  try {
    await ensureSettingsTable();

    if (!req.user || !['admin', 'moderator', 'super_admin'].includes(req.user.role)) {
      return res.status(403).json({ error: "Access denied. Administrative role required." });
    }

    const [inquiries] = await pool.query(
      `SELECT id, name, phone, email, subject, message, status, created_at
       FROM contact_inquiries
       ORDER BY created_at DESC`
    );

    return res.json({
      success: true,
      count: inquiries.length,
      inquiries
    });
  } catch (err) {
    console.error("getContactInquiries error:", err);
    return res.status(500).json({ error: "Failed to retrieve inquiries." });
  }
}

// PATCH /api/settings/contact-inquiries/:id - Mark as read/responded
export async function updateContactInquiryStatus(req, res) {
  try {
    await ensureSettingsTable();

    if (!req.user || !['admin', 'moderator', 'super_admin'].includes(req.user.role)) {
      return res.status(403).json({ error: "Access denied. Administrative role required." });
    }

    const inquiryId = parseInt(req.params.id, 10);
    const { status } = req.body;

    if (!status || !['unread', 'read', 'responded'].includes(status)) {
      return res.status(400).json({ error: "Invalid status value." });
    }

    await pool.query(
      `UPDATE contact_inquiries SET status = ? WHERE id = ?`,
      [status, inquiryId]
    );

    return res.json({ success: true, message: "Inquiry status updated." });
  } catch (err) {
    console.error("updateContactInquiryStatus error:", err);
    return res.status(500).json({ error: "Failed to update inquiry status." });
  }
}

// DELETE /api/settings/contact-inquiries/:id - Admin removal
export async function deleteContactInquiry(req, res) {
  try {
    await ensureSettingsTable();

    if (!req.user || !['admin', 'moderator', 'super_admin'].includes(req.user.role)) {
      return res.status(403).json({ error: "Access denied. Administrative role required." });
    }

    const inquiryId = parseInt(req.params.id, 10);
    await pool.query(`DELETE FROM contact_inquiries WHERE id = ?`, [inquiryId]);

    return res.json({ success: true, message: "Inquiry deleted successfully." });
  } catch (err) {
    console.error("deleteContactInquiry error:", err);
    return res.status(500).json({ error: "Failed to delete inquiry." });
  }
}
