<?php
declare(strict_types=1);
require_once __DIR__ . '/api/lib.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Handle both JSON and form data
        $input = [];
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        
        if (strpos($contentType, 'application/json') !== false) {
            $input = hw_input_json();
            $answers = $input['answers'] ?? [];
        } else {
            $answers = $_POST;
        }
        
        if (empty($answers)) {
            hw_json(['message' => 'No form data received'], 400);
        }
        
        // Basic validation
        if (empty($answers['first_name']) || empty($answers['last_name']) || empty($answers['email'])) {
            hw_json(['message' => 'Name and email are required'], 400);
        }
        
        $pdo = hw_db();
        
        // Check if user exists
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->execute([$answers['email']]);
        $existingUser = $stmt->fetch();
        
        $userId = null;
        
        if (!$existingUser && !empty($answers['password'])) {
            // Register new user
            $stmt = $pdo->prepare('INSERT INTO users (first_name, last_name, email, password_hash, status) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([
                $answers['first_name'],
                $answers['last_name'], 
                $answers['email'],
                hw_hash_password($answers['password']),
                'active'
            ]);
            $userId = (int)$pdo->lastInsertId();
            
            // Assign client role
            $stmt = $pdo->prepare('INSERT INTO user_roles (user_id, role_id) VALUES (?, 2)');
            $stmt->execute([$userId]);
        } else {
            $userId = $existingUser['id'] ?? null;
        }
        
        if ($userId) {
            // Save intake form
            $stmt = $pdo->prepare('INSERT INTO intake_forms (user_id, data, created_at) VALUES (?, ?, NOW())');
            $stmt->execute([$userId, json_encode($answers)]);
            
            // Create JWT token for auto-login
            $token = hw_jwt_encode(['sub' => $userId, 'email' => $answers['email']]);
            hw_set_auth_cookie($token);
            
            hw_json(['message' => 'Form submitted successfully', 'success' => true, 'redirect' => '/atasteofafricanmarketplace/dashboard/user/choose-plan.php']);
        } else {
            hw_json(['message' => 'User registration failed'], 500);
        }
        
    } catch (Exception $e) {
        error_log('Intake form error: ' . $e->getMessage());
        hw_json(['message' => 'Server error occurred'], 500);
    }
}

hw_json(['message' => 'Invalid request'], 400);
?>