<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    // Create help_settings table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS help_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(100) UNIQUE NOT NULL,
            setting_value TEXT NOT NULL,
            description TEXT,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_setting_key (setting_key),
            INDEX idx_is_active (is_active)
        )
    ");
    
    // Check if table has data, if not insert defaults
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM help_settings");
    $count = $stmt->fetch()['count'];
    
    if ($count == 0) {
        $pdo->exec("
            INSERT INTO help_settings (setting_key, setting_value, description, is_active) VALUES
            ('phone_number', '+91-9876543210', 'Support phone number for calls', TRUE),
            ('whatsapp_number', '919876543210', 'WhatsApp number for chat support', TRUE),
            ('email_address', 'support@astrosidhi.com', 'Support email address', TRUE),
            ('support_hours', '9:00 AM - 6:00 PM', 'Support available hours', TRUE),
            ('support_message', 'Hello, I need help with the Astro app.', 'Default WhatsApp message', TRUE)
        ");
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get all help settings
        $stmt = $pdo->prepare("
            SELECT 
                id,
                setting_key,
                setting_value,
                description,
                is_active,
                created_at
            FROM help_settings 
            ORDER BY id ASC
        ");
        $stmt->execute();
        $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'settings' => $settings,
            'total_settings' => count($settings)
        ]);
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $raw_input = file_get_contents('php://input');
        $input = json_decode($raw_input, true);
        
        if (!$input) {
            throw new Exception('Invalid JSON input');
        }
        
        $action = $input['action'] ?? '';
        
        switch ($action) {
            case 'update':
                updateHelpSetting($pdo, $input);
                break;
            default:
                throw new Exception('Invalid action');
        }
    } else {
        throw new Exception('Method not allowed');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}

function updateHelpSetting($pdo, $input) {
    if (empty($input['id'])) {
        throw new Exception('ID is required for update');
    }
    
    if (empty($input['setting_value'])) {
        throw new Exception('Setting value is required');
    }
    
    $stmt = $pdo->prepare("
        UPDATE help_settings SET 
            setting_value = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
    ");
    $stmt->execute([$input['setting_value'], $input['id']]);
    
    echo json_encode(['success' => true, 'message' => 'Help setting updated successfully']);
}
?>
