<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Authenticate user
$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    errorResponse('Unauthorized', 401);
}

// Grant Admin Unrestricted Privileges: Allow admin to view/edit anyone
$targetUserId = $user['id'];
$isAdmin = isAdmin($user['id']);

if ($isAdmin) {
    if (isset($_GET['userId'])) {
        $targetUserId = $_GET['userId'];
    } elseif (isset($input['userId'])) {
        $targetUserId = $input['userId'];
    }
}

// Determine action from URL path
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$action = basename($path);

try {
    switch ($action) {
        case 'get':
            // Fetch profile
            $stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
            $stmt->execute([$user['id']]);
            $profile = $stmt->fetch(PDO::FETCH_ASSOC);

            // Fetch settings
            $stmt = $pdo->prepare("SELECT * FROM user_settings WHERE user_id = ?");
            $stmt->execute([$user['id']]);
            $settings = $stmt->fetch(PDO::FETCH_ASSOC);

            // Fetch progress/stats
            $stmt = $pdo->prepare("SELECT * FROM user_progress WHERE user_id = ?");
            $stmt->execute([$user['id']]);
            $progress = $stmt->fetch(PDO::FETCH_ASSOC);

            jsonResponse([
                'profile' => $profile,
                'settings' => $settings,
                'progress' => $progress
            ], 200);
            break;

        case 'update':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                errorResponse('Method not allowed', 405);
            }

            $fields = ['first_name', 'last_name', 'username', 'phone', 'bio', 'location', 'skills'];
            $updates = [];
            $params = [];

            foreach ($fields as $field) {
                if (isset($input[$field])) {
                    $updates[] = "$field = ?";
                    $params[] = $input[$field];
                }
            }

            if (empty($updates)) {
                errorResponse('No fields to update', 400);
            }

            $params[] = $user['id'];
            $sql = "UPDATE user_profiles SET " . implode(', ', $updates) . ", updated_at = CURRENT_TIMESTAMP WHERE user_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            jsonResponse(['message' => 'Profile updated successfully'], 200);
            break;

        case 'update_settings':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                errorResponse('Method not allowed', 405);
            }

            $fields = [
                'email_notifications', 'push_notifications', 'sms_notifications', 
                'marketing_notifications', 'security_alerts', 'update_alerts',
                'two_factor_auth', 'session_timeout', 'password_expiry', 'login_alerts',
                'theme', 'compact_mode', 'show_animations', 'font_size'
            ];
            
            $updates = [];
            $params = [];

            foreach ($fields as $field) {
                if (isset($input[$field])) {
                    $updates[] = "$field = ?";
                    $params[] = $input[$field];
                }
            }

            if (empty($updates)) {
                errorResponse('No settings to update', 400);
            }

            $params[] = $user['id'];
            $sql = "UPDATE user_settings SET " . implode(', ', $updates) . ", updated_at = CURRENT_TIMESTAMP WHERE user_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            jsonResponse(['message' => 'Settings updated successfully'], 200);
            break;

        case 'change_password':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                errorResponse('Method not allowed', 405);
            }

            if (!isset($input['current_password']) || !isset($input['new_password'])) {
                errorResponse('Current and new password are required', 400);
            }

            // Verify current password
            $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
            $stmt->execute([$user['id']]);
            $userData = $stmt->fetch();

            if (!password_verify($input['current_password'], $userData['password_hash'])) {
                errorResponse('Invalid current password', 401);
            }

            // Update password
            $newHash = password_hash($input['new_password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$newHash, $user['id']]);

            jsonResponse(['message' => 'Password changed successfully'], 200);
            break;

        case 'upload_avatar':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                errorResponse('Method not allowed', 405);
            }

            if (!isset($_FILES['avatar'])) {
                errorResponse('No file uploaded', 400);
            }

            $file = $_FILES['avatar'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            
            if (!in_array($file['type'], $allowedTypes)) {
                errorResponse('Invalid file type. Only JPG, PNG, GIF, and WEBP are allowed.', 400);
            }
            
            // Limit size to 5MB
            if ($file['size'] > 5 * 1024 * 1024) {
                errorResponse('File too large. Maximum size is 5MB.', 400);
            }

            // Define upload directory relative to this file (backend/api)
            // We want to store in fcorex/public/uploads/avatars so it's accessible by frontend
            $uploadDir = __DIR__ . '/../../public/uploads/avatars/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = 'avatar_' . $user['id'] . '_' . uniqid() . '.' . $extension;
            $targetPath = $uploadDir . $filename;

            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                // Public URL path (relative to web root)
                $publicUrl = '/uploads/avatars/' . $filename;

                $stmt = $pdo->prepare("UPDATE user_profiles SET avatar_url = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?");
                $stmt->execute([$publicUrl, $user['id']]);

                jsonResponse(['message' => 'Avatar updated successfully', 'avatar_url' => $publicUrl], 200);
            } else {
                errorResponse('Failed to save file', 500);
            }
            break;

        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Profile error: ' . $e->getMessage(), 500);
}
