<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    sendResponse(false, 'Only PUT method allowed', null, 405);
}

try {
    $user = validateToken($conn);
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    $name = sanitizeInput($input['name'] ?? '');
    $email = sanitizeInput($input['email'] ?? '');
    $phone = sanitizeInput($input['phone'] ?? '');
    $mobile = sanitizeInput($input['mobile'] ?? '');
    $address = sanitizeInput($input['address'] ?? '');
    $instagram = sanitizeInput($input['instagram'] ?? '');
    $facebook = sanitizeInput($input['facebook'] ?? '');
    
    if (empty($name) || empty($email)) {
        sendResponse(false, 'Name and email are required', null, 400);
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(false, 'Invalid email format', null, 400);
    }
    
    // Check if email is already taken by another user
    $checkStmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $checkStmt->bind_param("si", $email, $user['id']);
    $checkStmt->execute();
    $checkStmt->store_result();
    
    if ($checkStmt->num_rows > 0) {
        sendResponse(false, 'Email already taken by another user', null, 409);
    }
    
    // Update profile
    $stmt = $conn->prepare("UPDATE users SET name=?, email=?, phone=?, mobile=?, address=?, instagram=?, facebook=? WHERE id=?");
    $stmt->bind_param("sssssssi", $name, $email, $phone, $mobile, $address, $instagram, $facebook, $user['id']);
    
    if ($stmt->execute()) {
        // Get updated profile
        $getStmt = $conn->prepare("SELECT id, name, email, phone, mobile, address, instagram, facebook, profile_image, created_at FROM users WHERE id = ?");
        $getStmt->bind_param("i", $user['id']);
        $getStmt->execute();
        $result = $getStmt->get_result();
        $updatedProfile = $result->fetch_assoc();
        
        sendResponse(true, 'Profile updated successfully', $updatedProfile);
    } else {
        sendResponse(false, 'Profile update failed', null, 500);
    }
    
    $stmt->close();
    $checkStmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Profile update failed: ' . $e->getMessage(), null, 500);
}
?>
