<?php
// Load CORS configuration FIRST
require_once './includes/cors.php';
configureCors();
//member-settings-api.php
require_once __DIR__ . '/includes/config_loader.php';
require_once __DIR__ . '/includes/config.php';

// Set JSON header
// Set response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Add security headers
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    header('Content-Length: 0');
    http_response_code(200);
    exit();
}
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['member_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit;
}

// Get current user
$userId = $_SESSION['member_id'];

// Handle different request methods
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($pdo, $userId);
            break;
            
        case 'POST':
        case 'PUT':
            handleUpdateRequest($pdo, $userId);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

/**
 * Handle GET request - get settings
 */
function handleGetRequest($pdo, $userId) {
    // Get specific setting or all settings
    if (isset($_GET['name'])) {
        $settingName = trim($_GET['name']);
        getSetting($pdo, $userId, $settingName);
    } else {
        getAllSettings($pdo, $userId);
    }
}

/**
 * Get all settings for user
 */
function getAllSettings($pdo, $userId) {
    $stmt = $pdo->prepare("SELECT * FROM member_settings WHERE member_id = ?");
    $stmt->execute([$userId]);
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format response
    $result = [];
    foreach ($settings as $setting) {
        $result[$setting['setting_name']] = [
            'value' => $setting['setting_value'],
            'two_factor_enabled' => (bool)$setting['two_factor_enabled'],
            'two_factor_method' => $setting['two_factor_method']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'settings' => $result
    ]);
}

/**
 * Get specific setting
 */
function getSetting($pdo, $userId, $settingName) {
    $stmt = $pdo->prepare("SELECT * FROM member_settings WHERE member_id = ? AND setting_name = ?");
    $stmt->execute([$userId, $settingName]);
    $setting = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$setting) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Setting not found']);
        return;
    }
    
    echo json_encode([
        'success' => true,
        'setting' => [
            'name' => $setting['setting_name'],
            'value' => $setting['setting_value'],
            'two_factor_enabled' => (bool)$setting['two_factor_enabled'],
            'two_factor_method' => $setting['two_factor_method']
        ]
    ]);
}

/**
 * Handle POST/PUT request - update settings
 */
function handleUpdateRequest($pdo, $userId) {
    // Get input data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
        return;
    }
    
    // Check if updating single or multiple settings
    if (isset($input['name']) && isset($input['value'])) {
        // Update single setting
        updateSingleSetting($pdo, $userId, $input);
    } elseif (isset($input['settings']) && is_array($input['settings'])) {
        // Update multiple settings
        updateMultipleSettings($pdo, $userId, $input['settings']);
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid request format']);
    }
}

/**
 * Update single setting
 */
function updateSingleSetting($pdo, $userId, $data) {
    $settingName = $data['name'];
    $settingValue = $data['value'];
    $twoFactorEnabled = $data['two_factor_enabled'] ?? null;
    $twoFactorMethod = $data['two_factor_method'] ?? null;
    
    // Check if setting exists
    $stmt = $pdo->prepare("SELECT id FROM member_settings WHERE member_id = ? AND setting_name = ?");
    $stmt->execute([$userId, $settingName]);
    $exists = $stmt->fetch();
    
    $now = date('Y-m-d H:i:s');
    
    if ($exists) {
        // Update existing
        $sql = "UPDATE member_settings SET 
                setting_value = ?, 
                two_factor_enabled = ?, 
                two_factor_method = ?, 
                updated_at = ? 
                WHERE member_id = ? AND setting_name = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $settingValue,
            $twoFactorEnabled,
            $twoFactorMethod,
            $now,
            $userId,
            $settingName
        ]);
        
        $action = 'updated';
    } else {
        // Insert new
        $sql = "INSERT INTO member_settings 
                (member_id, setting_name, setting_value, two_factor_enabled, two_factor_method, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $userId,
            $settingName,
            $settingValue,
            $twoFactorEnabled,
            $twoFactorMethod,
            $now,
            $now
        ]);
        
        $action = 'created';
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Setting ' . $action,
        'setting' => [
            'name' => $settingName,
            'value' => $settingValue,
            'two_factor_enabled' => $twoFactorEnabled,
            'two_factor_method' => $twoFactorMethod
        ]
    ]);
}

/**
 * Update multiple settings
 */
function updateMultipleSettings($pdo, $userId, $settings) {
    $results = [];
    $now = date('Y-m-d H:i:s');
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        foreach ($settings as $setting) {
            if (!isset($setting['name']) || !isset($setting['value'])) {
                throw new Exception('Invalid setting format');
            }
            
            $settingName = $setting['name'];
            $settingValue = $setting['value'];
            $twoFactorEnabled = $setting['two_factor_enabled'] ?? null;
            $twoFactorMethod = $setting['two_factor_method'] ?? null;
            
            // Check if exists
            $checkStmt = $pdo->prepare("SELECT id FROM member_settings WHERE member_id = ? AND setting_name = ?");
            $checkStmt->execute([$userId, $settingName]);
            $exists = $checkStmt->fetch();
            
            if ($exists) {
                // Update
                $sql = "UPDATE member_settings SET 
                        setting_value = ?, 
                        two_factor_enabled = ?, 
                        two_factor_method = ?, 
                        updated_at = ? 
                        WHERE member_id = ? AND setting_name = ?";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    $settingValue,
                    $twoFactorEnabled,
                    $twoFactorMethod,
                    $now,
                    $userId,
                    $settingName
                ]);
                
                $action = 'updated';
            } else {
                // Insert
                $sql = "INSERT INTO member_settings 
                        (member_id, setting_name, setting_value, two_factor_enabled, two_factor_method, created_at, updated_at) 
                        VALUES (?, ?, ?, ?, ?, ?, ?)";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    $userId,
                    $settingName,
                    $settingValue,
                    $twoFactorEnabled,
                    $twoFactorMethod,
                    $now,
                    $now
                ]);
                
                $action = 'created';
            }
            
            $results[] = [
                'name' => $settingName,
                'action' => $action,
                'value' => $settingValue
            ];
        }
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Settings updated successfully',
            'results' => $results,
            'total' => count($results)
        ]);
        
    } catch (Exception $e) {
        // Rollback on error
        $pdo->rollBack();
        throw $e;
    }
}