<?php
/**
 * Update Profile API
 * 
 * Handles real user profile updates
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials (no wildcard when credentials=true)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require user authentication
requireLogin(true);

// Load configuration and database connection
require_once 'config.php';
require_once 'db.php';

$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;

// Only handle POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

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

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON input']);
    exit;
}

// Validate required fields
$required_fields = ['name', 'email'];
foreach ($required_fields as $field) {
    if (empty($input[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => "Missing required field: $field"]);
        exit;
    }
}

$name = trim($input['name']);
$email = trim($input['email']);
$profilePicture = isset($input['profilePicture']) ? trim($input['profilePicture']) : null;
$password = isset($input['password']) ? trim($input['password']) : null;

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid email format']);
    exit;
}

try {
    // Get current user data for audit trail
    $stmt = $pdo->prepare("SELECT name, email, username FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Check if email is already taken by another user
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $stmt->execute([$email, $user_id]);
    if ($stmt->fetch()) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Email is already taken by another user']);
        exit;
    }
    
    // Detect optional columns for schema tolerance
    $hasProfilePic = false;
    $hasUpdatedAt = false;
    try {
        $c = $pdo->query("SHOW COLUMNS FROM users LIKE 'profile_picture'");
        $hasProfilePic = $c && $c->rowCount() > 0;
    } catch (Exception $ignore) { $hasProfilePic = false; }
    // Auto-create profile_picture column if missing
    if (!$hasProfilePic) {
        try {
            $pdo->exec("ALTER TABLE users ADD COLUMN profile_picture VARCHAR(255) NULL AFTER email");
            $hasProfilePic = true;
        } catch (Exception $ignore) { /* leave as false if cannot add */ }
    }
    try {
        $c2 = $pdo->query("SHOW COLUMNS FROM users LIKE 'updated_at'");
        $hasUpdatedAt = $c2 && $c2->rowCount() > 0;
    } catch (Exception $ignore) { $hasUpdatedAt = false; }

    // Build UPDATE dynamically
    $fields = ["name = ?", "email = ?"];
    $params = [$name, $email];
    if ($hasProfilePic) { $fields[] = "profile_picture = ?"; $params[] = $profilePicture; }
    if (!empty($password)) {
        $fields[] = "password = ?";
        $params[] = password_hash($password, PASSWORD_DEFAULT);
    }
    if ($hasUpdatedAt) { $fields[] = "updated_at = NOW()"; }
    $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
    $params[] = $user_id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    // Log profile update for security audit
    $changedFields = [];
    if ($oldData['name'] !== $name) $changedFields['name'] = ['old' => $oldData['name'], 'new' => $name];
    if ($oldData['email'] !== $email) $changedFields['email'] = ['old' => $oldData['email'], 'new' => $email];
    if (!empty($password)) $changedFields['password'] = ['old' => '[HIDDEN]', 'new' => '[CHANGED]'];
    if ($profilePicture !== null) $changedFields['profile_picture'] = ['new' => 'updated'];
    
    if (!empty($changedFields)) {
        $logStmt = $pdo->prepare("
            INSERT INTO security_logs 
            (action, user_id, ip_address, user_agent, details, created_at) 
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        
        $logStmt->execute([
            'profile_updated',
            $user_id,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            json_encode([
                'fields_changed' => array_keys($changedFields),
                'changes' => $changedFields,
                'username' => $oldData['username'] ?? 'unknown'
            ])
        ]);
    }
    
    echo json_encode([
        'success' => true, 
        'message' => 'Profile updated successfully'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to update profile: ' . $e->getMessage()]);
}
?>
