<?php
/**
 * Update User Data API
 * Allows admins to update user information
 */

session_start();

// Check if user is logged in as admin
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized - Please log in as admin']);
    exit;
}

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

if (!$input || !isset($input['user_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

try {
    require_once '../config/database.php';
    $db = new Database();
    $conn = $db->getConnection();
    
    $userId = $input['user_id'];
    
    // Build update query dynamically based on provided fields
    $updateFields = [];
    $params = [':user_id' => $userId];
    
    if (isset($input['first_name'])) {
        $updateFields[] = 'first_name = :first_name';
        $params[':first_name'] = $input['first_name'];
    }
    
    if (isset($input['last_name'])) {
        $updateFields[] = 'last_name = :last_name';
        $params[':last_name'] = $input['last_name'];
    }
    
    if (isset($input['email'])) {
        $updateFields[] = 'email = :email';
        $params[':email'] = $input['email'];
    }
    
    if (isset($input['phone_number'])) {
        $updateFields[] = 'phone_number = :phone_number';
        $params[':phone_number'] = $input['phone_number'];
    }
    
    if (isset($input['license_plate'])) {
        $updateFields[] = 'license_plate = :license_plate';
        $params[':license_plate'] = $input['license_plate'];
    }
    
    if (isset($input['dealership_name'])) {
        $updateFields[] = 'dealership_name = :dealership_name';
        $params[':dealership_name'] = $input['dealership_name'];
    }
    
    if (empty($updateFields)) {
        echo json_encode(['success' => false, 'message' => 'No fields to update']);
        exit;
    }
    
    $sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :user_id";
    
    $stmt = $conn->prepare($sql);
    $result = $stmt->execute($params);
    
    if ($result) {
        // Get updated user data
        $selectSql = "SELECT first_name, last_name, email, phone_number, license_plate, dealership_name FROM users WHERE id = :user_id";
        $selectStmt = $conn->prepare($selectSql);
        $selectStmt->execute([':user_id' => $userId]);
        $userData = $selectStmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true, 
            'message' => 'User data updated successfully',
            'data' => $userData
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update user data']);
    }
    
} catch (Exception $e) {
    error_log("Error updating user data: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
