<?php
/**
 * Extract all FAQs from faq/index.php and insert into database
 */
require_once dirname(__DIR__) . '/config.php';

$conn = get_db_connection();

// Create table if it doesn't exist
$conn->query("CREATE TABLE IF NOT EXISTS `faqs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `question` text NOT NULL,
  `answer` text NOT NULL,
  `display_order` int(11) DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `display_order` (`display_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

// Read FAQ page
$faq_file = dirname(__DIR__) . '/faq/index.php';
$content = file_get_contents($faq_file);

// Extract FAQs using regex - match toggle items
preg_match_all('/<div class="elementor-toggle-item">.*?<a class="elementor-toggle-title"[^>]*>(.*?)<\/a>.*?<div[^>]*class="elementor-tab-content"[^>]*>(.*?)<\/div>/s', $content, $matches, PREG_SET_ORDER);

$faqs = [];
foreach ($matches as $index => $match) {
    $question = trim(strip_tags($match[1]));
    $answer = trim($match[2]);
    
    // Clean up answer HTML
    $answer = preg_replace('/\s+/', ' ', $answer);
    
    if (!empty($question) && !empty($answer)) {
        $faqs[] = [
            'question' => $question,
            'answer' => $answer,
            'order' => $index + 1
        ];
    }
}

// Check if FAQs already exist
$existing = $conn->query("SELECT COUNT(*) as count FROM faqs");
$row = $existing->fetch_assoc();
$count = $row['count'];

if ($count == 0 && !empty($faqs)) {
    // Insert FAQs
    $stmt = $conn->prepare("INSERT INTO faqs (question, answer, display_order) VALUES (?, ?, ?)");
    $inserted = 0;
    foreach ($faqs as $faq) {
        $stmt->bind_param("ssi", $faq['question'], $faq['answer'], $faq['order']);
        if ($stmt->execute()) {
            $inserted++;
        }
    }
    $stmt->close();
    
    echo "Successfully extracted and inserted $inserted FAQs into database!\n";
    echo "\nFAQs found:\n";
    foreach ($faqs as $i => $faq) {
        echo ($i + 1) . ". " . substr($faq['question'], 0, 60) . "...\n";
    }
} else {
    echo "FAQs already exist in database ($count records) or no FAQs found.\n";
    echo "Found " . count($faqs) . " FAQs in the file.\n";
}
